getDerivedStateFromError
2024年03月06日
一、认识
static getDerivedStateFromError
当子组件(包括远亲组件)在渲染过程中抛出错误时,React
就会调用它。这使你可以显示错误消息而不是直接清理 UI
。通常,它与 componentDidCatch
一起使用,它可以让你将错误报告发送到某些分析服务。
二、语法
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// 更新状态,以便下一次渲染将显示后备 UI。
return { hasError: true };
}
componentDidCatch(error, info) {
// 示例“组件堆栈”:
// 在 ComponentThatThrows 中(由 App 创建)
// 在 ErrorBoundary 中(由 APP 创建)
// 在 div 中(由 APP 创建)
// 在 App 中
logErrorToMyService(error, info.componentStack);
}
render() {
if (this.state.hasError) {
// 你可以渲染任何自定义后备 UI
return this.props.fallback;
}
return this.props.children;
}
}
error
: 被抛出的错误。实际上,它通常是Error
的实例,但这并不能保证,因为JavaScript
允许 抛出 任何类型的值,包括字符串甚至是null
。