首页 > 解决方案 > 使用 ErrorBoundary 捕获后 React 仍然显示错误

问题描述

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

首先显示这个get:

自定义错误

然后一秒钟后显示:

初始错误

我该如何解决这个问题?

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

标签: javascriptreactjscreate-react-app

解决方案


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

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

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

如果你想摆脱它,这个答案可能会有所帮助。


推荐阅读