组件异常处理

  • componentDidCatch()

    componentDidCatch(error, info) 异常的处理。

    只能捕获组件树的异常,无法捕获这个方法内的异常。

    示例:

    定义一下异常处理组件:

    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    
      componentDidCatch(error, info) {
        this.setState({ hasError: true });
        window.console.log(error, info);
      }
    
      render() {
        if (this.state.hasError) {
          return <h1>Something went wrong.</h1>;
        }
        return this.props.children;
      }
    }
    

    使用这个异常组件:

    <ErrorBoundary>
      <MyWidget />
    </ErrorBoundary>
    

results matching ""

    No results matching ""