【问题标题】:ReactJS - ErrorBoundaries are not working as expectedReactJS - ErrorBoundaries 没有按预期工作
【发布时间】:2020-04-22 13:25:08
【问题描述】:

背景: 反应版本:16.13.1 浏览器:Chrome 版本 - 81.0.4044.122

虽然在下面的代码 sn-p 中使用了 ErrorBoundary,但它会在浏览器中抛出错误。 处理的错误显示几毫秒,然后实际错误显示在浏览器中。 有人可以帮我解决这个问题。

下面是完整的sn-p代码:


class CustomErrorBoundary extends Component {
  constructor(props) {
      super(props);
      this.state = { error: null, errorInfo: null };
    }

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

    render() {
      if (this.state.errorInfo) {
        // Error path
        return (
          <div>
            <h2>Something went wrong.</h2>
          </div>
        );
      }
      // Normally, just render children
      return this.props.children;
    }  
}

class BuggyComponent extends Component {
  constructor(props) {
      super(props);
      this.state = { Clicked: "false" };
      this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
      this.setState({
          Clicked: "true"
      });
    }

    render() {
      if (this.state.Clicked === "true") {
        // Simulate a JS error
        throw new Error('I crashed!');
      }
      return <button onClick={this.handleClick}>{this.props.Label}</button>;
    }
}

function App() {
  return (
    <div>
      <CustomErrorBoundary>
        <BuggyComponent Label="I catch exceptions"/>
      </CustomErrorBoundary>
    </div>
  );
}

export default App;

【问题讨论】:

    标签: reactjs react-error-boundary


    【解决方案1】:

    【讨论】:

    • 哦,是的,有道理。谢谢你的解释。
    猜你喜欢
    • 2019-12-04
    • 2021-10-19
    • 2020-03-18
    • 2012-06-14
    • 2014-11-15
    • 1970-01-01
    • 2012-07-02
    • 2011-09-07
    • 2013-03-03
    相关资源
    最近更新 更多