使用 ErrorBoundary 创建 React App 不显示错误消息

Create React App not showing error message with ErrorBoundary

我正在学习如何使用 componentDidCatch()。它看起来直截了当。它有效,但仍会在视图中显示完整的错误堆栈。

在单独的文件中:

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

在页面刷新时,我看到 Sorry, an error occurred 一秒钟,然后向用户显示完整的错误堆栈。这是 Create React App 的问题吗?我正在使用 React 16。

如文件所述

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

即使您使用 componentDidCatch 也会记录错误

检查这个 codepin

根据 this 问题 github,

On page refresh, I see Sorry, an error occurred for, literally, a second then the full error stack displaying to the user.

@DanAbramov 已经明确表示

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 消息隐藏在错误覆盖层后面

要检查错误是否确实存在,您可以检查元素并从 DOM 中删除叠加层,您将能够看到错误消息

检查这个 CodeSandbox:

完整的错误堆栈只是在您 运行 处于开发模式的应用程序时显示的覆盖图。它不会在生产中显示。 (您可以点击右上角的 'X' 按钮关闭它。)

错误边界有助于在生产中显示回退 UI。在开发中,您仍然可以看到该错误(如官方 React 文档中所述,这是故意的)。只需关闭十字图标,您就可以看到您的后备 UI.

static getDerivedStateFromError updates the state so when the component re-renders the fallback UI will be shown.

componentDidCatch is to log an error.