React捕获异常

React在组件渲染阶段,由于js错误引起的异常不应该造成整个应用的崩溃。为了解决此问题,React在16引入了一个新的概念-“error boundaries(错误边界) ”。

文章目录


error boundaries 可以捕获哪些异常?

  • 子组件的渲染
  • 生命周期函数
  • 构造函数

class 组件中与之相关的生命周期方法有:static getDrivedStateFromError()、componentDidCatch()。简单点儿的处理方式一般如下:

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>

 


 

在哪些场景使用?

这取决于你的应用的设计,你可以在路由组件的顶层组件外加入<ErrorBoundary/>,也可以细分报错的场景,在不同组件外部加入不同的<ErrorBoundary/>。

推荐一个库

react-error-boundary 不需要自己定义state和实现渲染逻辑,只需要关注发生错误的时候,渲染的UI。该库提供了基于 render-prop 、HOC和基础的使用方式。


总结

缺点:这种方式不能捕获这些错误:

  • 事件处理程序
  • 异步代码 (e.g. setTimeout or requestAnimationFrame callbacks)
  • 服务端的渲染代码
  • error boundaries自己抛出的错误
上一篇:Elasticsearch启动报错main ERROR Unable to locate appender "rolling_old" for logger config &quo


下一篇:华为2288h v5服务器安装esxi报错partedUtil setptbl...exited with status 255,Unable to commit to disk