React V16 錯誤處理(componentDidCatch 示例)

文章來源:ReactV16 Error Handler (componentDidCatch example) - A look at componentDidCatch and componentStack,React 交流羣::342685917javascript


React 早就須要一個處理錯誤的解決方案。html

在 React V15 中使用 handle_unstableError前端

從早期的 React 開發以來,一個小的組件拋出錯誤將會破壞整個應用程序,這種狀況至關廣泛。java

最近在 github 上證明,React Core 決定實現一個內置的函數叫作 componentDidCatch!我(原做者)我的也在 2015 年 10 月 21 日作了一些投入,可是從 2014 年 11 月 3 日纔開始正式跟蹤這個錯誤/解決方案!react

咱們再耐心等待 996 天!(譯者注:今天(2017-09-27) React 16 正式發佈)git

讓咱們來看看吧!

React 16 將提供一個內置函數 componentDidCatch,若是 render() 函數拋出錯誤,則會觸發該函數。在下面的示例中,你能夠點擊 「button will throw」 來拋出一個錯誤。github

在線示例:CodeSandbox微信

https://facebook.github.io/re...(中文:React 16 的異常/錯誤處理函數

重要提示:

錯誤在渲染階段中被捕獲,但在事件處理程序中不會被捕獲。示例按鈕 「button will not throw」 將不會使用錯誤邊界,但錯誤信息仍將顯示在 javascript 控制檯中。this

我強烈建議您點擊此代碼並查看示例組件。下面是一個基本的 PotentialError 組件

class PotentialError extends React.Component {   
  constructor(props) {     
    super(props);     
    this.state = { error: false };
  }
  componentDidCatch(error, info) {     
    this.setState({ error, info });
  }
  render() {
    if (this.state.error) {
      return <h1>Error: {this.state.error.toString()}</h1>;
    }
    return this.props.children;   
  } 
}

而後在頂部或任何地方,你能夠這樣使用它:

<PotentialError><AwesomeApp /></PotentialError>

另外一個使人敬畏的特性 componentDidCatch 是包含錯誤堆棧的 info 對象!

{this.state.info && this.state.info.componentStack}

這將告訴你組件在哪裏失效!

讓我知道你正在使用錯誤邊界!


歡迎關注個人公衆號,關注前端文章:

justjavac微信公衆號

相關文章
相關標籤/搜索