關于React16.0的componentDidCatch方法解讀
React16.0的componentDidCatch方法
這段時間看了下react一些新特性,想說說其中一個。
React 16 將提供一個內置函數(shù) componentDidCatch,如果 render() 函數(shù)拋出錯誤,該函數(shù)可以捕捉到錯誤信息,并且可以展示相應的錯誤信息,這個方法真的很贊!
那么componentDidCatch究竟可以做什么?有什么好處?
- 當有錯誤發(fā)生時, 我們可以友好地展示 fallback 組件;
- 可以捕捉到它的子元素(包括嵌套子元素)拋出的異常;
- 可以復用錯誤組件;
代碼詳解:
import React, { Component } from 'react' export default class App extends Component { render() { return ( <div> <PointerError> <SomeState></SomeState> </PointerError> </div> ) } } class PointerError extends Component { // PointerError是錯誤捕獲組件 constructor(props) { super(props) this.state = { error: false, text: '' } } // parseStr(str) { // 格式化位置組件錯誤信息 // let res = str.match(/in[^\(]+\(/g) // res = res.map(item => item.slice(3, -2)) // console.log('res', res) // } componentDidCatch(error, info) { console.log(error, info) alert('錯誤發(fā)生的位置:' + info.componentStack) //錯誤信息error.message, 錯誤堆棧error.stack, 組件堆棧info.componentStack this.setState({ error, info, text: info.componentStack }) } render() { if (this.state.error) { return ( <div> <h1>錯誤是:{this.state.error.toString()}</h1> <h2>錯誤出現(xiàn)的位置是:{this.state.text}</h2> <img src="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2942945378,442701149&fm=26&gp=0.jpg" /> </div> ) } return this.props.children } } class SomeState extends Component { constructor(props) { super(props) this.state = { error: false } } render() { throw new Error('我發(fā)生了錯誤') //報錯信息 return ( <div> <div>你已經(jīng)正確的打開了頁面</div> </div> ) } }
上面代碼中聲明了一個PointerError 組件和一個SomeState 組件,PointerError 就是我們說的錯誤提示組件,我在其子元素中(也就是SomeState 組件)拋出來一個錯誤,它內置的componentDidCatch()方法可以幫我們捕捉到錯誤信息,在控制臺打印可看到:
這樣的話就可以用一個錯誤信息頁面來代替由于某個組件報錯而頁面異常了
另一個特性
componentDidCatch 它也是一個包含錯誤堆棧的 info 對象,這將告訴你組件在哪里失效!
{this.state.info && this.state.info.componentStack}
React錯誤處理(componentDidCatch)
看react 文檔突然發(fā)現(xiàn)有這個 錯誤處理函數(shù),好像是17年9月出的,這個真的絕了可以幫助我們捕捉錯誤咯
React 16 將提供一個內置函數(shù) componentDidCatch,如果 render() 函數(shù)拋出錯誤,則會觸發(fā)該函數(shù)。
官網(wǎng)例子
下面這個:
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; } }
當然你可以把這個組件封裝下成為
<ErrorBoundary> ? <MyWidget /> </ErrorBoundary>
然后在頂部或任何地方,你可以這樣使用它
另一個特性:
componentDidCatch 是包含錯誤堆棧的 info 對象!
{this.state.info && this.state.info.componentStack}
當然我是這么用的在路由那邊
class App extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } componentDidCatch(error, info) { console.log(error, info) this.setState({ hasError: true }) } render() { return this.state.hasError ? <h2>頁面出錯了404</h2> : ( <React.Fragment> {/* 檢驗是否有登錄信息 */} <AutoRoute /> {/* 有了switch后,匹配到path后就不會再匹配下去了 */} <Switch> <Route path="/login" component={Login}></Route> <Route path='/register' component={Register}></Route> <Route path='/chat/:user' component={Chat}></Route> </Switch> </React.Fragment> ) } }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
react-redux action傳參及多個state處理的實現(xiàn)
本文主要介紹了react-redux action傳參及多個state處理的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07React中Suspense及l(fā)azy()懶加載及代碼分割原理和使用方式
這篇文章主要介紹了React中Suspense及l(fā)azy()懶加載及代碼分割原理和使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09