我正在努力处理多个错误边界。
让我在一些情况下进行解释:
App.js
<ErrorBoundary level="app">
<SomeComponents>
{/* ... */}
<BuggyComponent/>
<ErrorBoundary level="local">
<NestedBuggyComponent/>
</ErrorBoundary>
{/* ... */}
</SomeComponents>
</ErrorBoundary>
ErrorBoundary.js
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
console.log('ErrorBoundary triggered at level: ' + this.props.level);
this.setState({
error,
errorInfo
});
}
render() {
const { children, level } = this.props;
const { error, errorInfo } = this.state;
if (errorInfo) {
return <div>An error detected at level: {level}</div>;
}
return children;
}
}
在以下情况下,我正在寻找这样做:
如果NestedBuggyComponent
引发错误,而BuggyComponent
没有引发错误,则应显示:
<div>
<div>{...}</div>
<div>An error detected at level: local</div>
<div>{...}</div>
</div>
但实际上我有:
<div>An error detected at level: app</div>
这意味着它已被道具ErrorBoundary
顶住level="app"
如果我的组件之一崩溃,则必须由最近的ErrorBoundary
父级捕获。
NestedBuggyComponent
组件,必须由ErrorBoundary
用道具level="local"
捕获,并且其他组件仍应显示
BuggyComponent
组件,它必须由ErrorBoundary
用道具level="app"
捕获,并且只应显示一个错误
关于如何解决标准n°1 的任何建议?