ComponentDidCatch不起作用 [英] ComponentDidCatch does not work

查看:33
本文介绍了ComponentDidCatch不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 componentDidCatch 在我的本机应用程序中不起作用. componentDidCatch 不处理错误.

Why componentDidCatch does not work in my react-native app. componentDidCatch does not handle errors.

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()仅用于捕获由组件子代抛出的错误.在这里,似乎您正在尝试捕获由同一组件引发的错误-这将无法正常工作.

This doesn't work because componentDidCatch() only works for catching errors thrown by a components children. Here it seems like you are trying to catch an error thrown by the same component - that's not going to work.

请参见官方文档以获取更多信息:

See the official documentation for more info:

错误边界是React组件,它们在其子组件树中的任意位置捕获JavaScript错误,记录这些错误,并显示后备UI ,而不是崩溃的组件树.

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.

注意子组件树中的任何地方" .

因此,您所需要做的就是将您的组件包装在另一个组件中,该组件可以管理所有引发的错误.像这样:

So all you need to do is to wrap your component inside another component that manages all errors thrown. Something like:

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

这篇关于ComponentDidCatch不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆