React 錯誤處理(componentDidCatch)


前言

   看react 文檔突然發現有這個 錯誤處理函數,好像是17年9月出的,這個真的絕了可以幫助我們捕捉錯誤咯

 

 React 16 將提供一個內置函數 componentDidCatch,如果 render() 函數拋出錯誤,則會觸發該函數。

官網例子

下面這個:

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>
      )
  }
}

其實還是組件化比較好一點,畢竟復用性比較高


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM