React文檔篇-錯誤邊界

錯誤邊界

react組件,能夠用來捕獲並打印其子組件樹任何位置的JavaScript錯誤,可渲染備用UIjavascript

錯誤邊界沒法捕獲一下場景的錯誤java

  • 異步代碼
  • 事件處理
  • 服務端渲染
  • 它自身拋出來的錯誤

usage:

一個class組件定義了以上兩個鉤子中任意一個即爲錯誤邊界組件react

  1. static getDerivedStateFromError(error) 渲染備用UI
  2. componentDidCatch(error, info) 打印錯誤信息,上傳至服務器
// 簡單實現一個錯誤邊界
import React, { Component } from 'react'

import { logErrToMyService } from '../util/index'

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

  componentDidCatch(error, info) {
    logErrToMyService(error, info);
  }

  static getDerivedStateFromError(error) {
    // 在這裏更新state使下一次渲染顯示降級的UI
    return {
      hasError: true
    }
  }

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

export default ErrorBoundary;
複製代碼

事件處理

針對事件處理拋出的異常,因爲它不是在渲染期間拋出的問題,固React渲染並不會受到影響,而且能在控制檯打印出來,官方推薦,若是須要捕獲事件處理的錯誤,使用try/catch語句便可服務器

import React, { Component } from 'react'

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 1,
      error: null
    }
  }

  handleClick() {
    const self = this;
    try {
      this.setState({
        count: self.state.count++
      })
    } catch (err) {
      console.log(err)
      this.setState({ error: self.state.error });
    }
  }

  render() {
    if(this.state.error) {
      return (
        <div>MyComponent has err</div>
      )
    }
    return (
      <div className="mycomponent"> <button onClick={this.handleClick.bind(this)}>change</button> </div>
    )
  }
}

export default MyComponent;
複製代碼

即便一個組件發生在componentDidUpdate,而且是因爲深層組件的一個setState操做引發的,其仍然夠冒泡到最近的錯誤邊界被捕獲異步

相關文章
相關標籤/搜索