Mai*_*eyy 18 javascript reactjs create-react-app
我的React应用程序正在捕获错误并正确显示我的自定义错误消息,但一秒钟后它仍然显示原始错误记录.因此,后备UI然后被初始错误屏幕取代.
测试组件:
import React, { Component } from 'react';
export class Test extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ErrorBoundary>
<Error></Error>
</ErrorBoundary>);
}
}
Run Code Online (Sandbox Code Playgroud)
错误组件:
import React, { Component } from 'react';
export class Error extends React.Component {
constructor(props) {
super(props);
}
render() {
return ({ test });
}
}
Run Code Online (Sandbox Code Playgroud)
在错误组件测试中未定义,因此将抛出未定义的错误.
ErrorBoundary:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
首先显示以下内容:
然后在一秒钟之后显示以下内容:
我怎么解决这个问题?
如果组件崩溃,ErrorBoundaries可以防止崩溃所有内容并在该组件中显示自定义消息并使其他组件保持活动(正确),对吧?
caf*_*ech 35
我想我明白了.该create-react-app软件包有一个名为react-overlay-error的工具.这会将来自控制台的错误消息显示为应用程序上的覆盖,以便您可以轻松检查堆栈跟踪和调试.
这不会出现在生产模式中,它只是一个复制普通浏览器控制台的开发工具.
您可以通过按Escape再次查看叠加来隐藏此功能.
如果你想摆脱它,这个答案可能会有所帮助.
| 归档时间: |
|
| 查看次数: |
2268 次 |
| 最近记录: |