reactjs - ReactJS - ErrorBoundaries 没有按预期工作
问题描述
背景:React 版本:16.13.1 浏览器:Chrome 版本 - 81.0.4044.122
尽管在下面的代码片段中使用了 ErrorBoundary,但它会在浏览器中引发错误。处理的错误显示几毫秒,然后实际错误显示在浏览器中。有人可以帮我解决这个问题。
下面是整个代码片段:
class CustomErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
class BuggyComponent extends Component {
constructor(props) {
super(props);
this.state = { Clicked: "false" };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
Clicked: "true"
});
}
render() {
if (this.state.Clicked === "true") {
// Simulate a JS error
throw new Error('I crashed!');
}
return <button onClick={this.handleClick}>{this.props.Label}</button>;
}
}
function App() {
return (
<div>
<CustomErrorBoundary>
<BuggyComponent Label="I catch exceptions"/>
</CustomErrorBoundary>
</div>
);
}
export default App;
解决方案
推荐阅读
- swift - 快速转义反斜杠无法按预期工作
- java - 转换 Observable onError 并发出一个项目
- line-breaks - 如何使用 reStructuredText 创建新行?
- docker - 在使用 docker compose 3 启动我的应用程序之前,我应该如何确定 DB 已启动
- php - Android 应用内购买验证问题:无法解析代码,返回值始终为零
- r - 我正在尝试将包含相同列标题的 25 个文件逐行追加到 R 中的单个数据框中
- asp.net-core-signalr - ASP.NET Core SignalR 客户端 WSS 问题
- go - 将 JSON 解组为 struct - 列表中的列表类型?
- reactjs - Material UI 1.3.1 文本字段没有 onKeyPress 方法
- r - 使用 R 和 purrr 使用带有 pmap 的列表列表连接多个数据帧