Error Boundaries(錯誤邊界)是React 16+引入的一個新概念,那麼具體是什麼東西呢? 異步
話很少說,先看官方怎麼說:ide
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
這段文字信息量很大,須要拆成兩部分來看函數
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed.
簡單翻譯過來就是:錯誤邊界是一個組件,這個組件能夠用來捕獲它的子組件中產生的錯誤,記錄錯誤日誌並在錯誤發生的是,展現一個「回退」或者說是一個錯誤信息頁面,以免由於局部組件錯誤而致使的整個組件樹崩潰。this
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
簡單翻譯過來就是說: 錯誤邊界能夠在捕獲其 其子組件的渲染、生命週期函數以及構造函數內的錯誤。翻譯
既然叫錯誤邊界,一方面,能夠理解成這個組件是全部子組件發送錯誤的捕獲者,全部子組件的錯誤到達錯誤邊界組件後,錯誤信息被攔截並再也不向上冒泡,因此這個組件就是錯誤的一個邊界;另外一方面,也能夠理解成攔截錯誤的能力是有邊界的,不是全部錯誤均可以捕獲,那具體什麼錯誤能夠捕獲什麼不能捕獲呢? 日誌
上面已經提到,錯誤邊界能夠攔截子組件的渲染、生命週期函數以及構造函數內的錯誤。簡單的說就是子組件聲明週期內的錯誤。code
Event handlers 事件處理函數觸發的錯誤 Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks) 異步代碼 Server side rendering 服務端渲染 Errors thrown in the error boundary itself (rather than its children) 本身產生的錯誤
原則上來說,錯誤邊界是用來保證React能夠正常渲染UI的,而不是真的用來捕獲異常的。component
當非生命週期函數中發生錯誤的時候,React依然能夠保證UI渲染能夠完成,只是可能會有錯誤提示。。。生命週期
因此,正確的作法應該是在聲明週期中的錯誤用錯誤邊界來處理,其它地方的錯誤依然使用 try。。catch。。事件
仍是先看官方示例:
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info): class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // 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 <h1>Something went wrong.</h1>; } return this.props.children; } }
一個聲明瞭componentDidCatch生命週期函數的類組件,自動變成一個邊界組件。而後就能夠像普通組件同樣使用了
<ErrorBoundary> <MyWidget /> </ErrorBoundary>
錯誤邊界僅能夠捕獲其子組件的錯誤。錯誤邊界沒法捕獲其自身的錯誤。若是一個錯誤邊界沒法渲染錯誤信息,則錯誤會向上冒泡至最接近的錯誤邊界。這也相似於 JavaScript 中 catch {} 的工做機制。
自 React 16 開始,任何未被錯誤邊界捕獲的錯誤將會卸載整個 React 組件樹。