【问题标题】:Why is Error boundary in React JS not working为什么 React JS 中的错误边界不起作用
【发布时间】:2019-06-02 17:31:08
【问题描述】:

我有一个组件

import React, {Component} from 'react';

class Buggy extends Component {
    state = {greeting : 'Welcome'};

    componentDidMount() {
        throw new Error('An error has occured');
    }

    render() {
        return (
            <h2>{this.state.greeting}</h2>
        );
    }
}

export default Buggy;

还有一个典型的ErrorBoundary

import React, {Component} from 'react';

class ErrorBoundary extends Component {
    state = {error: null, errorInfo: null};

    componentDidCatch(error, errorInfo) {
        this.setState({
            error: error,
            errorInfo: errorInfo
        })
    }

    render() {
        if(this.state.errorInfo) {
            return (
                <div>
                    <h2>Oops! Something went wrong.</h2>
                </div>
            );
        }
        return this.props.children;
    }
}

export default ErrorBoundary;

App.js

  <ErrorBoundary>
    <Buggy />
  </ErrorBoundary>
</Fragment>

但错误没有得到处理。

我做错了什么?

【问题讨论】:

  • 我认为render() 之外的组件错误不会被捕获,因为在反应源中,这里适用的代码大致是try{ render() } catch(e) { ... } 我也注意到了这一点,所以我们使用了一个工作在我们的渲染方法中以一种轮回的方式抛出渲染中的所有错误。我们确实有一个像&lt;ThrowError error={this.state.error} /&gt; 这样的组件,它的所有渲染方法都是throw this.props.error

标签: javascript reactjs error-handling


【解决方案1】:

componentDidCatch() 用于记录错误信息而不是呈现回退 UI,为此使用 getDerivedStateFromError()。

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

Error Boundaries

【讨论】:

  • 它确实处理了回退。
猜你喜欢
  • 2011-10-21
  • 2019-02-20
  • 2022-07-06
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
相关资源
最近更新 更多