ReactJS-ErrorBounders未按预期工作

ReactJS-ErrorBounders未按预期工作,reactjs,react-error-boundary,Reactjs,React Error Boundary,背景: 反应版本:16.13.1 浏览器:Chrome版本-81.0.4044.122 尽管在下面的代码段中使用了ErrorBoundary,但它会在浏览器中引发错误。 已处理的错误显示数毫秒,然后实际错误显示在浏览器中。 有人能帮我解决这个问题吗 下面是完整的代码片段: class CustomErrorBoundary extends Component { constructor(props) { super(props); this.state = { er

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

尽管在下面的代码段中使用了ErrorBoundary,但它会在浏览器中引发错误。 已处理的错误显示数毫秒,然后实际错误显示在浏览器中。 有人能帮我解决这个问题吗

下面是完整的代码片段:


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;

类CustomErrorBoundary扩展组件{
建造师(道具){
超级(道具);
this.state={error:null,errorInfo:null};
}
componentDidCatch(错误,errorInfo){
//捕获下面任何组件中的错误,并使用错误消息重新渲染
这是我的国家({
错误:错误,
errorInfo:errorInfo
})
//您还可以在此处将错误消息记录到错误报告服务
}
render(){
if(this.state.errorInfo){
//错误路径
返回(
出了点问题。
);
}
//通常,只渲染子对象
返回此.props.children;
}  
}
类BuggyComponent扩展组件{
建造师(道具){
超级(道具);
this.state={单击:“false”};
this.handleClick=this.handleClick.bind(this);
}
handleClick(){
这是我的国家({
点击:“正确”
});
}
render(){
如果(this.state.Clicked==“true”){
//模拟一个JS错误
抛出新错误(“我崩溃了!”);
}
返回{this.props.Label};
}
}
函数App(){
返回(
);
}
导出默认应用程序;

这是非生产版本中的默认行为


哦,是的,这很有道理。谢谢你的解释。