Day 14:Error Boundary
错误边界
组件的"保险丝",出错时不让页面崩溃
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
logError(error, info); // 上报服务器
}
render() {
if (this.state.hasError) {
return <div>出错了: {this.state.error.message}</div>;
}
return this.props.children;
}
}
// 使用
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
限制
只能捕获子组件的错误,不能捕获:
- 事件处理函数中的错误
- 异步代码错误
- 服务端渲染错误
自测答案
- 作用:捕获子组件错误,防止白屏
- 实现:getDerivedStateFromError + componentDidCatch
- 限制:不能捕获事件、异步错误