【问题标题】:Possible to dismiss the browser compile error and show the react errorboundary?可以消除浏览器编译错误并显示反应错误边界吗?
【发布时间】:2019-09-11 08:41:14
【问题描述】:

我有一个应用程序,我想在其中实现 reacts errorboundary:

import React, { Component } from 'react'
import ErrorView from './components/ErrorView'

class ErrorBoundary extends Component {
  state = {
    hasError: false,
  }

  static getDerivedStateFromError(error: any) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true }
  }
  componentDidCatch(error: any, info: any) {
    // Display fallback UI
    this.setState({ hasError: true })
    console.log('error', error)
    console.log('info', info)
    console.log('I have error')
    // You can also log the error to an error reporting service
    // logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <ErrorView />
    } else {
      return this.props.children
    }
  }
}

export default ErrorBoundary

我将我的应用程序放在错误边界内:

ReactDOM.render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>,
  document.getElementById('root')
)

在应用程序组件的其中一个子组件中,我创建了一个尝试映射空数组的组件。我这样做是为了得到一个错误,并希望能得到我的错误视图。

会发生什么: 我收到一个错误,errorView 被显示,但在我收到红框错误消息后一秒钟:

TypeError: 无法读取未定义的属性“地图”

这是在开发环境中,坦率地说,在我确认只有错误视图会显示之前,我害怕将其投入生产,

有没有办法抑制浏览器中的错误呈现? 我仍然在控制台中收到错误,我只是不希望它在浏览器渲染中。

【问题讨论】:

    标签: javascript reactjs compiler-errors


    【解决方案1】:

    没关系,错误覆盖是开发环境的一部分,你可以关闭它看看你的ErrorView

    生产构建后,覆盖将被禁用,所有错误将被定向到ErrorView

    要禁用 error-overlay refer to this question,您需要在 webpack 配置中 eject 并禁用 webpackHotDevClient(强烈不推荐)。

    或添加到您的全局 CSS:

    iframe {
        display: none;
    }
    

    如果您想知道错误边界实际上做了什么,check this question

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 2018-06-10
      • 2021-12-03
      • 1970-01-01
      • 2017-03-27
      • 2018-06-15
      相关资源
      最近更新 更多