關(guān)于React16.0的componentDidCatch方法解讀
React16.0的componentDidCatch方法
這段時(shí)間看了下react一些新特性,想說(shuō)說(shuō)其中一個(gè)。
React 16 將提供一個(gè)內(nèi)置函數(shù) componentDidCatch,如果 render() 函數(shù)拋出錯(cuò)誤,該函數(shù)可以捕捉到錯(cuò)誤信息,并且可以展示相應(yīng)的錯(cuò)誤信息,這個(gè)方法真的很贊!
那么componentDidCatch究竟可以做什么?有什么好處?
- 當(dāng)有錯(cuò)誤發(fā)生時(shí), 我們可以友好地展示 fallback 組件;
- 可以捕捉到它的子元素(包括嵌套子元素)拋出的異常;
- 可以復(fù)用錯(cuò)誤組件;
代碼詳解:
import React, { Component } from 'react' export default class App extends Component { render() { return ( <div> <PointerError> <SomeState></SomeState> </PointerError> </div> ) } } class PointerError extends Component { // PointerError是錯(cuò)誤捕獲組件 constructor(props) { super(props) this.state = { error: false, text: '' } } // parseStr(str) { // 格式化位置組件錯(cuò)誤信息 // 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('錯(cuò)誤發(fā)生的位置:' + info.componentStack) //錯(cuò)誤信息error.message, 錯(cuò)誤堆棧error.stack, 組件堆棧info.componentStack this.setState({ error, info, text: info.componentStack }) } render() { if (this.state.error) { return ( <div> <h1>錯(cuò)誤是:{this.state.error.toString()}</h1> <h2>錯(cuò)誤出現(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ā)生了錯(cuò)誤') //報(bào)錯(cuò)信息 return ( <div> <div>你已經(jīng)正確的打開(kāi)了頁(yè)面</div> </div> ) } }
上面代碼中聲明了一個(gè)PointerError 組件和一個(gè)SomeState 組件,PointerError 就是我們說(shuō)的錯(cuò)誤提示組件,我在其子元素中(也就是SomeState 組件)拋出來(lái)一個(gè)錯(cuò)誤,它內(nèi)置的componentDidCatch()方法可以幫我們捕捉到錯(cuò)誤信息,在控制臺(tái)打印可看到:
這樣的話就可以用一個(gè)錯(cuò)誤信息頁(yè)面來(lái)代替由于某個(gè)組件報(bào)錯(cuò)而頁(yè)面異常了
另一個(gè)特性
componentDidCatch 它也是一個(gè)包含錯(cuò)誤堆棧的 info 對(duì)象,這將告訴你組件在哪里失效!
{this.state.info && this.state.info.componentStack}
React錯(cuò)誤處理(componentDidCatch)
看react 文檔突然發(fā)現(xiàn)有這個(gè) 錯(cuò)誤處理函數(shù),好像是17年9月出的,這個(gè)真的絕了可以幫助我們捕捉錯(cuò)誤咯
React 16 將提供一個(gè)內(nèi)置函數(shù) componentDidCatch,如果 render() 函數(shù)拋出錯(cuò)誤,則會(huì)觸發(fā)該函數(shù)。
官網(wǎng)例子
下面這個(gè):
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; } }
當(dāng)然你可以把這個(gè)組件封裝下成為
<ErrorBoundary> ? <MyWidget /> </ErrorBoundary>
然后在頂部或任何地方,你可以這樣使用它
另一個(gè)特性:
componentDidCatch 是包含錯(cuò)誤堆棧的 info 對(duì)象!
{this.state.info && this.state.info.componentStack}
當(dāng)然我是這么用的在路由那邊
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>頁(yè)面出錯(cuò)了404</h2> : ( <React.Fragment> {/* 檢驗(yàn)是否有登錄信息 */} <AutoRoute /> {/* 有了switch后,匹配到path后就不會(huì)再匹配下去了 */} <Switch> <Route path="/login" component={Login}></Route> <Route path='/register' component={Register}></Route> <Route path='/chat/:user' component={Chat}></Route> </Switch> </React.Fragment> ) } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法
這篇文章主要為大家介紹了ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn)
本文主要介紹了react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07React中Suspense及l(fā)azy()懶加載及代碼分割原理和使用方式
這篇文章主要介紹了React中Suspense及l(fā)azy()懶加載及代碼分割原理和使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09React通過(guò)conetxt實(shí)現(xiàn)多組件傳值功能
Context 提供了一種在組件之間共享此類值的方式,而不必顯式地通過(guò)組件樹(shù)的逐層傳遞 props。本文給大家介紹React通過(guò)conetxt實(shí)現(xiàn)多組件傳值功能,感興趣的朋友一起看看吧2021-10-10