React 在使用 ErrorBoundary 捕获后仍然显示错误

React still showing errors after catching with ErrorBoundary

我的 React 应用正在捕获错误并正确显示我的自定义错误消息,但一秒钟后它仍然显示原始错误日志记录。所以后备 UI 然后被初始错误屏幕所取代。

测试组件:

import React, { Component } from 'react';

export class Test extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
        <ErrorBoundary>

        <Error></Error>

        </ErrorBoundary>);
    }
}

错误成分:

import React, { Component } from 'react';

export class Error extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return ({ test });
    }
}

在错误组件test中未定义,所以会抛出一个未定义的错误。

错误边界:

import React, { Component } from 'react';

export class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { error: null, errorInfo: null };
        console.log('initiated');
    }

    componentDidCatch(error, errorInfo) {
        // Catch errors in any components below and re-render with error message
        console.log('ERROR');
        this.setState({
            error: error,
            errorInfo: errorInfo
        })
        // You can also log error messages to an error reporting service here
    }

    render() {
        console.log('STATE');
        console.log(this.state.error);
        if (this.state.errorInfo) {
            // Error path
            return (
                <div>
                    <h2>Something went wrong.</h2>
                    <details style={{ whiteSpace: 'pre-wrap' }}>
                        {this.state.error && this.state.error.toString()}
                        <br />
                        {this.state.errorInfo.componentStack}
                    </details>
                </div>
            );
        }
        // Normally, just render children
        return this.props.children;
    }
}

首先显示的是:

然后在一秒钟后显示:

我该如何解决这个问题?

如果一个组件崩溃,ErrorBoundaries 可以防止所有崩溃并在该组件中显示自定义消息并使其他组件保持活动状态(完好无损),对吗?

我想我明白了。 create-react-app 包有一个名为 react-overlay-error 的工具。这会将来自控制台的错误消息显示为您的应用程序的叠加层,以便您可以轻松检查堆栈跟踪和调试。

这不会出现在生产模式中,它只是一个复制普通浏览器控制台的开发工具。

您可以通过按 Escape 再次查看叠加层来隐藏它。

如果您想摆脱它, 可能会有所帮助。