【问题标题】:ComponentDidCatch does not workComponentDidCatch 不起作用
【发布时间】:2017-11-10 13:22:00
【问题描述】:

为什么 componentDidCatch 在我的 react-native 应用程序中不起作用。 componentDidCatch 不处理错误。

React native v: 50.3
React: 16.0.0

import React, {Component} from 'react';
import {View, Text}        from 'react-native';
import Logo               from './SignUpInit/Logo';
import SignUp             from './SignUpInit/SignUp';
import Social             from './SignUpInit/Social';
import styles             from './SignUpInit/styles';

export default class SignUpInit extends Component {

    state = {
        componentCrashed: false,
        count: 0,
    }

    componentDidCatch(error, info) {
        console.log(error);
        console.log(info);
        console.log('_______DID CATCH____________');
        this.setState({componentCrashed: true});
    }

    componentDidMount(){
        setInterval(()=>this.setState({count: this.state.count+1}),1000);
    }

    render() {
        if (this.state.componentCrashed) {
            return (
                <View>
                    <Text>
                        Error in component "SingUpInit"
                    </Text>
                </View>
            );
        }

        if(this.state.count > 5){
            throw new Error('Error error error');
        }


        return (
            <View style={styles.main}>
                <Logo/>
                <SignUp/>
                <Social/>
            </View>
        );
    }
}

【问题讨论】:

  • 如果您希望其他人提供帮助,您将需要提供更多详细信息。在此处发布代码,如果可能,请提供可重现的示例
  • 您需要提供更多详细信息。什么不起作用?你期望会发生什么?能否提供相关代码或工作示例?
  • 您需要提供更多详细信息。发布您的组件,究竟是什么不起作用?你怎么知道?

标签: javascript reactjs react-native


【解决方案1】:

这不起作用,因为componentDidCatch() 仅适用于捕获子组件抛出的错误。在这里,您似乎正试图捕捉由同一组件引发的错误 - 这是行不通的。

查看official documentation了解更多信息:

错误边界是 React 组件,它在其子组件树的任何位置捕获 JavaScript 错误,记录这些错误,并显示一个备用 UI,而不是显示崩溃的组件树。

注意“在他们的子组件树中的任何地方”


因此,您需要做的就是将您的组件包装在另一个组件中,该组件管理所有抛出的错误。比如:

<ErrorBoundary>
  <SignUpInit />
</ErrorBoundary>

&lt;ErrorBoundary /&gt; 的含义很简单:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {hasError: false};
  }

  componentDidCatch(error, info) {
    this.setState({hasError: true});
  }

  render() {
    if(this.state.hasError) return <div>Error!</div>;
    return this.props.children;
  }
}

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 2020-05-12
    • 2018-12-07
    • 2019-12-03
    • 2018-08-02
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多