Error Boundaries(错误边界)是React 16+引入的一个新概念,那么具体是什么东西呢? 异步
话很少说,先看官方怎么说:ide
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
这段文字信息量很大,须要拆成两部分来看函数
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
简单翻译过来就是:错误边界是一个组件,这个组件能够用来捕获它的子组件中产生的错误,记录错误日志并在错误发生的是,展现一个“回退”或者说是一个错误信息页面,以免由于局部组件错误而致使的整个组件树崩溃。this
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
简单翻译过来就是说: 错误边界能够在捕获其 其子组件的渲染、生命周期函数以及构造函数内的错误。翻译
既然叫错误边界,一方面,能够理解成这个组件是全部子组件发送错误的捕获者,全部子组件的错误到达错误边界组件后,错误信息被拦截并再也不向上冒泡,因此这个组件就是错误的一个边界;另外一方面,也能够理解成拦截错误的能力是有边界的,不是全部错误均可以捕获,那具体什么错误能够捕获什么不能捕获呢? 日志
上面已经提到,错误边界能够拦截子组件的渲染、生命周期函数以及构造函数内的错误。简单的说就是子组件声明周期内的错误。code
Event handlers 事件处理函数触发的错误 Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) 异步代码 Server side rendering 服务端渲染 Errors thrown in the error boundary itself (rather than its children) 本身产生的错误
原则上来说,错误边界是用来保证React能够正常渲染UI的,而不是真的用来捕获异常的。component
当非生命周期函数中发生错误的时候,React依然能够保证UI渲染能够完成,只是可能会有错误提示。。。生命周期
因此,正确的作法应该是在声明周期中的错误用错误边界来处理,其它地方的错误依然使用 try。。catch。。事件
仍是先看官方示例:
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info): 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; } }
一个声明了componentDidCatch生命周期函数的类组件,自动变成一个边界组件。而后就能够像普通组件同样使用了
<ErrorBoundary> <MyWidget /> </ErrorBoundary>
错误边界仅能够捕获其子组件的错误。错误边界没法捕获其自身的错误。若是一个错误边界没法渲染错误信息,则错误会向上冒泡至最接近的错误边界。这也相似于 JavaScript 中 catch {} 的工做机制。
自 React 16 开始,任何未被错误边界捕获的错误将会卸载整个 React 组件树。