React 基礎篇(八)—— 錯誤邊界

錯誤邊界

過去,組件內的 JS 錯誤會導致 React 的內部狀態被破壞,並且再下一次渲染時產生可能無法追蹤的錯誤。部分 UIJS 錯誤不應該導致整個應用崩潰,爲了解決這個問題,引入了錯誤邊界的概念。

錯誤邊界是一種 React 組件,這種組件可以捕獲並打印發生在其子組件樹任何位置的 JS 錯誤,並且它具有渲染備用 UI 的能力。

錯誤邊界可以在渲染期間、生命週期方法和整個組件樹的構造函數中捕獲錯誤。

如果一個 class 組件定義了 static getDerivedStateFromError()componentDidCatch() 這兩個方法之一時,它就變成一個錯誤邊界。當拋出錯誤後,使用前者渲染備用 UI ,使用後者打印錯誤信息。

注意:錯誤邊界僅可以捕獲其子組件的錯誤,無法鋪貨其自身的錯誤。

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能夠顯示降級後的 UI
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    // 你同樣可以將錯誤日誌上報給服務器
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定義降級後的 UI 並渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章