为什么React JS中的错误边界不起作用

时间:2019-06-02 17:31:08

标签: javascript reactjs error-handling

我有一个组件

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>

尚未处理错误。

enter image description here

我在做什么错了?

1 个答案:

答案 0 :(得分:-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