我正在尝试学习如何在 React js 中使用错误边界。正如我在这里读到的那样,它可以防止您的应用程序崩溃。但是我的应用程序崩溃了!这是我的代码:
应用组件:
function App() {
return (
<>
<h1>app component</h1>
<ErrorBoundary >
<Simple />
</ErrorBoundary>
</>
);
}
Run Code Online (Sandbox Code Playgroud)
简单组件:
export default () => {
throw new Error('I crashed!')
return <h3> simple component</h3>
}
Run Code Online (Sandbox Code Playgroud)
这是我的边界=
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.
console.log("I got you ")
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
console.log(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Run Code Online (Sandbox Code Playgroud)
在很短的时间内,我看到消息“出了点问题”,但在那之后页面崩溃了!
感谢您的帮助和建议
如果应用程序在开发环境中崩溃,这是预期行为,以便开发人员可以解决问题。
ErrorBoundaries 应该只在生产环境中工作而不会崩溃。