React V16 错误处理(componentDidCatch 示例)

文章来源:ReactV16 Error Handler (componentDidCatch example) – A look at componentDidCatch and componentStack,React 交流群::342685917

React 早就需要一个处理错误的解决方案。

在 React V15 中使用 handle_unstableError

从早期的 React 开发以来,一个小的组件抛出错误将会破坏整个应用程序,这种情况相当普遍。

最近在 github 上证实,React Core 决定实现一个内置的函数叫做 componentDidCatch!我(原作者)个人也在 2015 年 10 月 21 日做了一些投入,但是从 2014 年 11 月 3 日才开始正式跟踪这个错误/解决方案!

我们再耐心等待 996 天!(译者注:今天(2017-09-27) React 16 正式发布)

让我们来看看吧!

React 16 将提供一个内置函数 componentDidCatch,如果 render() 函数抛出错误,则会触发该函数。在下面的示例中,你可以点击 “button will throw” 来抛出一个错误。

在线示例:CodeSandbox

https://facebook.github.io/re…(中文:React 16 的异常/错误处理

重要提示:

错误在渲染阶段中被捕获,但在事件处理程序中不会被捕获。示例按钮 “button will not throw” 将不会使用错误边界,但错误信息仍将显示在 javascript 控制台中。

我强烈建议您点击此代码并查看示例组件。下面是一个基本的 PotentialError 组件

class PotentialError extends React.Component {   
  constructor(props) {     
    super(props);     
    this.state = { error: false };
  }
  componentDidCatch(error, info) {     
    this.setState({ error, info });
  }
  render() {
    if (this.state.error) {
      return <h1>Error: {this.state.error.toString()}</h1>;
    }
    return this.props.children;   
  } 
}

然后在顶部或任何地方,你可以这样使用它:

<PotentialError><AwesomeApp /></PotentialError>

另一个令人敬畏的特性 componentDidCatch 是包含错误堆栈的 info 对象!

{this.state.info && this.state.info.componentStack}

这将告诉你组件在哪里失效!

让我知道你正在使用错误边界!

欢迎关注我的公众号,关注前端文章:

《React V16 错误处理(componentDidCatch 示例)》

    原文作者:justjavac
    原文地址: https://segmentfault.com/a/1190000011379425
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞