Skip to content

Instantly share code, notes, and snippets.

@shengoo
Created April 20, 2018 15:17
Show Gist options
  • Save shengoo/a697da57a5db2cc1ddad7be7085f280e to your computer and use it in GitHub Desktop.
Save shengoo/a697da57a5db2cc1ddad7be7085f280e to your computer and use it in GitHub Desktop.

使用componentDidCatch处理React中的Uncaught error

React 16 提供了一个内置的函数componentDidCatch, 它会在render抛出异常的时候运行。

官方的示例代码如下:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

使用的时候

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

我们可以在出错的时候,显示错误信息,并且上报错误信息到服务器。

它的工作方式和JavaScript中的catch{}一样

但是componentDidCatch这种声明式的用法,更符合React的思想。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment