gpt4 book ai didi

javascript - 如何优雅地防止 native react 崩溃?

转载 作者:行者123 更新时间:2023-12-05 00:31:56 26 4
gpt4 key购买 nike

当发生任何错误(语法、未定义、类型错误等)时,我想优雅地显示一个空 View
这是我尝试过的,但它似乎并没有优雅地失败。整个应用程序仍然会因此实现而崩溃。

const Parent = (props) => {
try{
return (<Child/>) //if Child logic crashes for any reason, return a blank view.
}catch(err){
return <View/>
}
}

最佳答案

您可以使用ErrorBoundary https://reactjs.org/docs/error-boundaries.html

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 };
}

componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}

render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}

return this.props.children;
}
}
在根项目中使用(示例 App.js )
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>

关于javascript - 如何优雅地防止 native react 崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68533702/

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