我的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; } }
首先显示此信息:
然后一秒钟后,将显示以下内容:
我该如何解决?
如果某个组件崩溃,ErrorBoundaries可以防止所有组件崩溃,并在该组件中显示自定义消息并使其他组件保持活动状态(对)?
我想我明白了。该create-react-app软件包有一个称为react-overlay- error的工具。这会将来自控制台的错误消息显示为应用程序的覆盖,因此您可以轻松地检查堆栈跟踪和调试。
create-react-app
这不会在生产模式下显示,它只是复制普通浏览器控制台的开发工具。
您可以通过按 Escape 再次显示叠加层来隐藏它。
如果您想摆脱它,此答案可能会有所帮助。