1 什么是错误边界
简单理解:专门给崩溃UI的备用UI组件,即原UI发生错误导致无法正常显示崩溃时的处理(一般都有备用UI),他能捕获其内部的组件树上任何js错误
注意,无法捕获场景
事件处理(事件处理是逻辑部分,不影响UI)
异步代码
服务端渲染
错误边界组件本身错误
2 定义一个错误边界组件
错误边界是一个组件!内部必须要定义两个方法:static getDerivedStateFromError
和componentDidCatch
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染能够显示降级后的 UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// 你同样可以将错误日志上报给服务器
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// 你可以自定义降级后的 UI 并渲染
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
3 使用错误边界组件
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
自 React 16 起,任何未被错误边界捕获的错误将会导致整个 React 组件树被卸载。