如果一个 class 组件中定义了 [static getDerivedStateFromError()](https://zh-hans.reactjs.org/docs/react-component.html#static-getderivedstatefromerror) 或 [componentDidCatch()](https://zh-hans.reactjs.org/docs/react-component.html#componentdidcatch) 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。当抛出错误后,请使用 static getDerivedStateFromError() 渲染备用 UI ,使用 componentDidCatch() 打印错误信息。
class ErrorBoundary extends React.Component {constructor(props) {super(props);this.state = { hasError: false };}static getDerivedStateFromError(error) {// 更新 state 使下一次渲染能够显示降级后的 UIreturn { hasError: true };}componentDidCatch(error, errorInfo) {// 你同样可以将错误日志上报给服务器logErrorToMyService(error, errorInfo);}render() {if (this.state.hasError) {// 你可以自定义降级后的 UI 并渲染return <h1>Something went wrong.</h1>;}return this.props.children;}}
主要是记不能被捕获到错误的情况:
- 事件处理
- 异步代码(例如
setTimeout或requestAnimationFrame回调函数) - 服务端渲染
- 它自身抛出来的错误(并非它的子组件)
踩了第4个的坑…
