简介
错误边界是一种 React 组件,这种组件可以捕获并打印发生在其子组件树任何位置的 JavaScript 错误,并且,它会渲染出备用 UI,而不是渲染那些崩溃了的子组件树。
如果一个 class 组件中定义了 static getDerivedStateFromError() 或 componentDidCatch() 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。当抛出错误后,请使用 static getDerivedStateFromError() 渲染备用 UI ,使用 componentDidCatch() 打印错误信息。
错误边界的用法详见官网: 错误边界。
异常处理流程分析
子组件异常可以分为两种: render 异常和 commit 异常。
render 异常,即在 constructor、componentWillMount、componentDidMount、render、shouldComponentUpdate、函数式组件方法、getDerivedStateFromProps、componentWillReceiveProps 执行过程中发生异常。
commit 异常,即在 componentDidMount、componentDidUpdate、getSnapshotBeforeUpdate、componentWillUnmount、函数式组件 effect、函数组件 layEffect 执行过程中发生异常。
不同类型的异常, react 的处理流程不同。
-
render 异常处理流程
render 异常处理流程大致如下:
-
commit 异常处理流程
commit 异常处理流程大致如下:
总结
综上,在使用错误边界时, 我们要注意以下内容:
-
子组件发生异常,react 会寻找离它最近的且定义getDerivedStateFromError、componentDidCatch 的父组件进行异常处理。
-
子组件发生异常,如果父组件没有捕获措施,react 会使用 console.error 打印异常信息。
-
使用 getDerivedStateFromError 处理子组件异常信息时,要启用备用渲染,否则异常处理无效,最后还是使用 console.error 打印异常信息。
-
父组件同时定义 getDerivedStateFromError 和 componentDidCatch,如果使用 getDerivedStateFromError 处理异常信息时,没有启用备用渲染, componentDidCatch 不会触发, 异常处理无效,最后还是使用 console.error 打印异常信息。
-
子组件 commit 阶段发生异常,如果父组件定义 getDerivedStateFromError 且没有启用备用渲染,会导致异常处理无效,而且会陷入死循环。