javascript - 我们可以在父级中捕获错误但在子级中实现回退 - React Error Boundary
问题描述
我试图在 React 中实现错误边界。这是我的组件
export const withErrorBoundary = WrappedComponent =>
class extends Component<Props, State> {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch = (error, errorInfo) => {
this.setState({
error,
errorInfo,
});
// TODO: log error messages, report error
};
render() {
if (this.state.errorInfo) {
return handleError(this.state.error, this.state.errorInfo);
}
// just render children
return <WrappedComponent {...this.props} />;
}
};
const handleError = (error, errorInfo) => (
<div>
<h2>Something went wrong.</h2>
<details>
{error?.toString()}
<br />
{errorInfo.componentStack}
</details>
</div>
);
以及我如何使用它
const Parent = () => {
return (<>
<div>Fixed Text</>
<Child /> // --> This component need to replace
</>
}
export withErrorBoundary(Parent);
所以基本上用这个当前的实现,只要有一些错误Parent
,整个Parent
将回退到handleError()
,(显示“出错了”)
但是,我只希望Child
组件被替换,并且<div>Fixed Text</>
仍然出现在Parent
. 反正有没有改变我的代码来实现这一点?
解决方案
推荐阅读
- angular - 如何从Angular http post返回OKObjectResult作为字符串
- reactjs - 使用 Apollo react 用于 S3 图像上传的 useMutation 加载器
- machine-learning - 非凸优化
- css - 如何从左到右逐渐改变元素的背景颜色
- java - 有没有办法验证正则表达式在 Java 中完全匹配?
- python - Keras:keras 模型的二阶导数始终为 0
- angular - 无法在页面加载时将值设置回角度选择下拉列表
- conda - 如何将非代码文件添加到 conda 包?
- javascript - 带有虚拟填充的猫鼬自定义模式/类型适用于 Model.populate 但不适用于 Document.populate
- arrays - Mongoose:无法在 Mongoose 数组 SchemaType 中添加一项。虽然可以添加不止一个