2017-10-19 200 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