我的 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 可以防止所有内容崩溃并在该组件中显示自定义消息并使其他组件保持活动状态(机智),对吗?