javascript - ComponentDidCatch 不起作用

标签 javascript reactjs react-native

为什么 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>
        );
    }
}

最佳答案

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

参见 official documentation了解更多信息:

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.

请注意“在其子组件树中的任意位置”


因此,您需要做的就是将您的组件包装在另一个管理所有抛出错误的组件中。像这样的东西:

<ErrorBoundary>
  <SignUpInit />
</ErrorBoundary>

在哪里<ErrorBoundary />就像这样简单:

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;
  }
}

关于javascript - ComponentDidCatch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223765/

相关文章:

javascript - 当 jquery 过滤器没有返回结果时在 div 中显示消息

reactjs - 如何禁用来自 React Native API 的某些特定项目的可触摸不透明度

javascript - 在react js中独立更改<td>的颜色

html - 为什么我转移到手机后查看文档更新?

javascript - ReactJS 通过 onClick 函数传递 key

react-native - 在 React Native 中使用 ScrollViews 水平和垂直滚动

javascript - React native : Component not defined? 无法导入?

javascript - Socket.io 在新连接上触发断开事件

javascript - JSFiddle 下拉按钮不可点击

javascript - 检查内部带有mysql调用的for循环是否完成nodejs