gpt4 book ai didi

reactjs - 为什么即使我使用错误边界,我的 react 应用程序也会崩溃?

转载 作者:行者123 更新时间:2023-12-04 00:59:47 25 4
gpt4 key购买 nike

我正在尝试学习如何在 React js 中使用错误边界。正如我所读 here它可以防止您的应用程序崩溃。但是我的应用程序崩溃了!这是我的代码:

应用组件:

function App() {
return (
<>
<h1>app component</h1>
<ErrorBoundary >
<Simple />
</ErrorBoundary>
</>
);
}

简单组件:

export default () => {
throw new Error('I crashed!')
return <h3> simple component</h3>
}

这是我的边界=

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;

在很短的时间内,我看到消息“出了点问题”,但之后页面崩溃了!

感谢您的帮助和建议

最佳答案

如果应用程序在开发环境中崩溃,这是预期的行为,以便开发人员可以解决问题。

ErrorBoundaries 应该只在生产环境中工作而不会崩溃。

关于reactjs - 为什么即使我使用错误边界,我的 react 应用程序也会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com