【问题标题】:How to get more useful error messages?如何获得更多有用的错误信息?
【发布时间】:2016-07-10 10:00:26
【问题描述】:

每当我尝试访问 undefined 时,React + ES6 Babel 都会吐出以下错误消息(例如尝试 person.age where person === undefined.)

当我输入错误的 import 语句或在解构 props 对象时出错时也会发生这种情况。例如,我可能会犯以下错误:

const { name, age } = this.props.person
// but `this.props.person` only has a `name` property.

这样缺少错误消息是一种痛苦。有没有我错过设置的选项?大家是如何应对这个问题的?

【问题讨论】:

    标签: reactjs ecmascript-6 babeljs


    【解决方案1】:

    这是一个非常需要的功能,可能会在下一个 React 版本中实现。现在您可以使用redbox-react。据我所知,react-transform-catch-errors 已弃用。

    /* global __DEV__ */
    import React from 'react'
    import { render } from 'react-dom'
    import App from './components/App'
    
    const root = document.getElementById('root')
    
    if (__DEV__) {
      const RedBox = require('redbox-react').default
      try {
        render(<App />, root)
      } catch (e) {
        render(<RedBox error={e} />, root)
      }
    } else {
      render(<App />, root)
    }
    

    【讨论】:

    • 似乎react-redboxreact-transform-catch-errors 都被react-hot-loader 弃用了,但我在应用react-hot-loader 后仍然遇到不友好的错误
    • redbox-react 非常适合我。尝试将 output.devtoolModuleFilenameTemplate = '/[resource-path]' 添加到 webpack 配置 - github.com/KeywordBrain/redbox-react#sourcemaps-with-webpack
    • 对此有任何更新吗?下一个版本的 React 已经发布了……有什么钩子可以让这变得简单/更好吗?
    【解决方案2】:

    是的,这很烦人。一种有帮助的方法是用 try / catch 包装每个 React 组件的渲染方法,这样你就可以看到实际的错误,而不是 React 提供的乱码。将此添加到您的 babel.js-config 中,它会自动完成:https://github.com/gaearon/react-transform-catch-errors

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-17
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多