其他分享
首页 > 其他分享> > React捕获异常

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和基础的使用方式。


总结

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

标签:boundaries,渲染,捕获,React,state,error,组件,异常
来源: https://blog.csdn.net/SandyoneU1993/article/details/118076611