当使用 react-boundary 并抛出手动错误时,错误边界有效!问题是,在 1-2 秒后,它会呈现错误,就好像没有错误边界一样
这是代码
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
console.log('has error', this.state);
if ((this.state as any).hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function Bomb(): any {
const a = null;
return <span>{a.b.c}</span>;
}
function App() {
const [explode, setExplode] = React.useState(false);
return (
<div>
<button onClick={() => setExplode((e) => !e)}>toggle explode</button>
<ErrorBoundary>{explode ? <Bomb /> : null}</ErrorBoundary>
</div>
);
}