ErrorBoundary 组件
- 监听所有下级组件报错,可降级展示UI
- 只监听组件渲染时报错,不监听
DOM
事件、异步错误 - 备用 UI:当
Error Boundary
捕获到错误时,它会渲染一个备用的UI,而不是导致整个组件树崩溃。 production
环境生效,dev
会直接抛出错误
代码示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: null };
}
static getDerivedStateFromError(error) {
// 更新state使下一次渲染能够显示降级后的UI
return { hasError };
}
componentDidCatch(error, errorInfo) {
// 你同样可以将错误日志上报给服务器
console.log(error, errorInfo);
}
render() {
if (this.state.hasError) {
// 你可以自定义降级后的UI并渲染
return <h1>渲染错误提示</h1>;
}
// 没有报错 直接渲染子组件
return this.props.children;
}
}
export default ErrorBoundary
在根入口文件中使用,监听所有组件错误
1
2
3
4
5
6
7
8
9
// index.jsx
import ErrorBoundary from './ErrorBoundary'
ReactDOM.render(
<ErrorBoundary>
<APP />
</ErrorBoundary>,
document. getElementById ('root')
)
事件报错
ErrorBoundary
不会监听DOM 事件报错- 可用
try-catch
- 可用
window.onerror