2017-10-19 202 views
1

我开始使用create-react-app一个应用程序,并且我有这个Error Boundary组分:阵营16错误边界部件(使用componentDidCatch)表示未被捕获的错误

import React from 'react' 

export default class ErrorBoundary extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { hasError: false }; 
    } 

    componentDidCatch(error, info) { 
    console.log('shouldnt I see this logged??') 

    this.setState({ hasError: true }); 
    } 

    render() { 
    if (this.state.hasError) { 
     return <h1>Something went wrong.</h1>; 
    } 

    return this.props.children; 
    } 
} 

我用它在这个应用组件:

import React from 'react' 
import ErrorBoundary from './ErrorBoundary' 


class App extends React.Component { 
    render() { 
    return (
     <ErrorBoundary> 
     <div> 
      <button onClick={() => { throw new Error('lets throw an error') }}> 
      Click to throw error 
      </button> 
     </div> 
     </ErrorBoundary> 
    ); 
    } 
} 

export default App; 

我期待如果我点击App中的按钮,应该捕获抛出的错误,我应该看到这从ErrorBoundary记录:“我不应该看到这个记录??”。但是,我没有看到,记录和它打破了应用:

enter image description here

我误解的东西吗?

+1

嘿,你做了什么看起来很对我,我只是测试,它失败了。所以我也有兴趣回答:) –

回答

1

没有任何事情发生的原因是这是事件处理程序中的错误,并且这些错误不会被错误边界捕获。该error-handling blog post分清哪些错误被发现:

错误边界渲染过程中发现错误,在生命周期的方法,并在下面他们整棵树的构造。

没有错误的界限,这些错误会非常棘手赶上(在阵营16,甚至生命周期方法的错误会让你的整个应用程序的渲染消失。)

编辑:actual docs都显得更加清晰关于哪些错误被捕获。另请注意,create-react-app使用react-error-overlay软件包,该软件包在dev-server上的构建将在短时间后用错误屏幕替换整个渲染。为了更好地查看您的错误,您可以运行生产版本。

+0

哦,我没有在文档中看到。这些信息在我所链接的博客文章中看起来并不明显。很高兴知道。谢谢。 – chevin99