文章来源:ReactV16 Error Handler (componentDidCatch example) - A look at componentDidCatch and componentStack,React 交流群::342685917javascript
React 早就须要一个处理错误的解决方案。html
在 React V15 中使用 handle_unstableError前端
从早期的 React 开发以来,一个小的组件抛出错误将会破坏整个应用程序,这种状况至关广泛。java
最近在 github 上证明,React Core 决定实现一个内置的函数叫作 componentDidCatch!我(原做者)我的也在 2015 年 10 月 21 日作了一些投入,可是从 2014 年 11 月 3 日才开始正式跟踪这个错误/解决方案!react
咱们再耐心等待 996 天!(译者注:今天(2017-09-27) React 16 正式发布)git
React 16 将提供一个内置函数 componentDidCatch
,若是 render()
函数抛出错误,则会触发该函数。在下面的示例中,你能够点击 “button will throw” 来抛出一个错误。github
在线示例:CodeSandbox微信
https://facebook.github.io/re...(中文:React 16 的异常/错误处理)函数
错误在渲染阶段中被捕获,但在事件处理程序中不会被捕获。示例按钮 “button will not throw” 将不会使用错误边界,但错误信息仍将显示在 javascript 控制台中。this
我强烈建议您点击此代码并查看示例组件。下面是一个基本的 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}
这将告诉你组件在哪里失效!
让我知道你正在使用错误边界!
欢迎关注个人公众号,关注前端文章: