javascript - 使用 ErrorBoundary 捕获后 React 仍然显示错误
问题描述
我的 React 应用程序正在捕获错误并正确显示我的自定义错误消息,但一秒钟后它仍然显示原始错误日志记录。因此,后备 UI 会被初始错误屏幕所取代。
测试组件:
import React, { Component } from 'react';
export class Test extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ErrorBoundary>
<Error></Error>
</ErrorBoundary>);
}
}
错误组件:
import React, { Component } from 'react';
export class Error extends React.Component {
constructor(props) {
super(props);
}
render() {
return ({ test });
}
}
在错误组件中 test 是未定义的,所以会抛出未定义的错误。
错误边界:
import React, { Component } from 'react';
export class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
console.log('initiated');
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
console.log('ERROR');
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
console.log('STATE');
console.log(this.state.error);
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
首先显示这个get:
然后一秒钟后显示:
我该如何解决这个问题?
如果组件崩溃,ErrorBoundaries 可以防止所有内容崩溃并在该组件中显示自定义消息并保持其他组件处于活动状态(完好无损),对吗?
解决方案
我想我明白了。该create-react-app
软件包有一个名为react-overlay-error的工具。这会将来自控制台的错误消息显示为覆盖在您的应用程序上,以便您可以轻松检查堆栈跟踪和调试。
这不会出现在生产模式中,它只是一个复制普通浏览器控制台的开发工具。
您可以通过按Escape再次查看叠加层来隐藏它。
如果你想摆脱它,这个答案可能会有所帮助。
推荐阅读
- shell - 使用 JQ 添加新对象后更新文件
- prestashop - prestashop 1.7 - 简单模块不起作用
- vb.net - 在 vb.net 中除以两倍是错误的
- tfs - 释放变量从文件中而不是在 TFS 中赋值
- c# - SNS - JSON 消息正文无法解析
- javascript - Google Apps 脚本从 Date() 获取当前月份
- python - 在 python 中从 DynamoDB 加载数据时获取 UnicodeEncodeError
- android - Google Play 商店下载/安装监听器
- ios - React Native App Transport Security 已阻止
- php - 在 WordPress 管理区域内调用插件页面