如果错误边界是错误类的实例,则错误边界不会授予对错误的访问权限

Arr*_*rro 3 reactjs react-16

我遇到了一个奇怪的行为。看看这个小提琴。当使用React 16错误处理机制,即Error Boundary时,我注意到参数error为空。经过进一步调查,我意识到只有在抛出 Error 对象时才会出现这种情况,如下所示:

throw new Error('The world is very strange')

但是,当以这种方式抛出错误时:

throw 'The world is very strange'

该错误将在 中出现componentDidCatch

请有人赐教。我希望继续使用,new Error因为建议使用它,并且它应该可以访问文件和抛出的行号。

我们来看一下代码。

class Boundary extends React.Component {
    constructor() {
      super();
      this.state = {}
    }

    componentDidCatch(error, info) {
       this.setState({
        error,
        info,
      })
    }

  render() {
    if (this.state.error) {
       return (
       <div>
         {JSON.stringify(this.state)}
       </div>)
    }
    return this.props.children;
   }
}

class Component extends React.Component {
    render() {
  // Why and what should i do ?
    throw 'This will be available in the error parameter'
    throw new Error('This one will not')
  }
}

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (
    <Boundary>
      <div>
        <Component />
      </div>
    </Boundary>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

bal*_*pha 5

该错误实际上是可用的。问题是它JSON.stringify不会序列化Error对象,并且由于这是您用来显示错误的内容,因此错误看起来像是空的。

这是您的小提琴的更新版本,它显式输出state.error.message,并且它可以工作。