创建React应用程序不显示带有ErrorBoundary的错误消息 [英] Create React App not showing error message with ErrorBoundary
问题描述
我正在学习如何使用 componentDidCatch()
。它看起来直截了当。可以,但是仍然可以在视图上显示完整的错误堆栈。
I'm learning how to use componentDidCatch()
. It looks straight forward. It works, but to still show the complete error stack on view.
在单独的文件中:
import React, { Component } from 'react'
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
}
}
componentDidCatch(error, info) {
console.log("Catching an error") // this is never logged
this.setState(state => ({...state, hasError: true }))
}
render() {
if (this.state.hasError) { return <div>Sorry, an error occurred</div> }
return this.props.children
}
}
export default ErrorBoundary
...
import React, { Component } from 'react'
class Foo extends Component {
render() {
return this.props.a.b; // So this should cause the error
}
}
export default Foo
...
import React, { Component } from 'react'
// Imported Foo and ErrorBoundary
class Home extends Component {
render() {
return <ErrorBoundary><Foo /></ErrorBoundary>
}
}
export default Home
页面刷新时,我看到抱歉,发生错误
一秒钟,然后向用户显示完整错误堆栈。这是Create React App的问题吗?我正在使用React 16。
On page refresh, I see Sorry, an error occurred
for, literally, a second then the full error stack displaying to the user. Is this an issue with Create React App? I'm using React 16.
推荐答案
按照 此 问题在github上
As per this issue on github,
在页面刷新时,我看到很抱歉,错误发生了一个字面上的
秒,然后向用户显示了完整的错误堆栈。
@DanAbramov已明确指出
@DanAbramov has made it clear that
这是故意的。意外错误仍然是错误。 (我们不建议
使用错误边界来处理预期的错误或控制流。)
This is intentional. An unexpected error is still an error. (We don’t recommend using error boundaries for expected errors or control flow.)
错误边界主要对生产有用,但在
中开发中,我们希望使错误尽可能地可见。
Error boundaries are primarily useful for production, but in development we want to make errors as highly visible as possible.
也可见的错误只是一个覆盖层,而您的 ErrorBoundary
消息被隐藏在错误叠加层后面
Also The error visible is just an overlay and your ErrorBoundary
message gets hidden behind the Error overlay
要检查错误是否确实存在,您可以检查元素并从DOM中删除叠加层,您将可以看到错误消息
To check if the Error is actually present, you can inspect element and delete the overlay from DOM, and you would be able to see the error message
选中此 CodeSandbox :
这篇关于创建React应用程序不显示带有ErrorBoundary的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!