詳解React 16 中的異常處理,react異常處理

來源:互聯網
上載者:User

詳解React 16 中的異常處理,react異常處理

詳解React 16 中的異常處理

異常處理

在 React 15.x 及之前的版本中,組件內的異常有可能會影響到 React 的內部狀態,進而導致下一輪渲染時出現未知錯誤。這些組件內的異常往往也是由應用代碼本身拋出,在之前版本的 React 更多的是交託給了開發人員處理,而沒有提供較好地組件內優雅處理這些異常的方式。在 React 16.x 版本中,引入了所謂 Error Boundary 的概念,從而保證了發生在 UI 層的錯誤不會連鎖導致整個應用程式崩潰;未被任何異常邊界捕獲的異常可能會導致整個 React 組件樹被卸載。所謂的異常邊界即指某個能夠捕獲它的子項目(包括嵌套子項目等)拋出的異常,並且根據使用者配置進行優雅降級地顯示而不是導致整個組件樹崩潰。異常邊界能夠捕獲渲染函數、生命週期回調以及整個組件樹的建構函式中拋出的異常。

我們可以通過為某個組件添加新的 componentDidCatch(error, info) 生命週期回調來使其變為異常邊界:

class ErrorBoundary extends React.Component { constructor(props) {super(props);this.state = { hasError: false }; } componentDidCatch(error, info) {  // Display fallback UIthis.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 UIreturn <h1>Something went wrong.</h1>;  }return this.props.children; }}

然後我們就可以如常使用該組件:

<ErrorBoundary><MyWidget /></ErrorBoundary>

componentDidCatch() 方法就好像針對組件的 catch {} 代碼塊;不過 JavaScript 中的 try/catch 模式更多的是面向命令式代碼,而 React 組件本身是聲明式模式,因此更適合採用指定渲染對象的模式。需要注意的是僅有類組件可以成為異常邊界,在真實的應與開發中我們往往會聲明單個異常邊界然後在所有可能拋出異常的組件中使用它。另外值得一提的是異常邊界並不能捕獲其本身的異常,如果異常邊界組件本身拋出了異常,那麼會冒泡傳遞到上一層最近的異常邊界中。

在真實地應用開發中有的開發人員也會將崩壞的介面直接展示給開發人員,不過譬如在某個聊天介面中,如果在出現異常的情況下仍然直接將介面展示給使用者,就有可能導致使用者將資訊發送給錯誤的接受者;或者在某些支付應用中導致使用者金額顯示錯誤。因此如果我們將應用升級到 React 16.x,我們需要將原本應用中沒有被處理地異常統一包裹進異常邊界中。譬如某個應用中可能會分為側邊欄、資訊面板、會話介面、資訊輸入等幾個不同的模組,我們可以將這些模組包裹進不同的錯誤邊界中;這樣如果某個組件發生崩潰,會被其直屬的異常邊界捕獲,從而保證剩餘的部分依然處於可用狀態。同樣的我們也可以在異常邊界中添加錯誤反饋等服務介面以及時反饋生產環境下的異常並且修複他們。完整的應用代碼如下所示:

class ErrorBoundary extends React.Component {constructor(props) {super(props);this.state = { error: null, errorInfo: null }; } componentDidCatch(error, errorInfo) {  // Catch errors in any components below and re-render with error messagethis.setState({   error: error,   errorInfo: errorInfo  })  // You can also log error messages to an error reporting service here } render() {if (this.state.errorInfo) {   // Error pathreturn (    <div>     <h2>Something went wrong.</h2>     <details style={{ whiteSpace: 'pre-wrap' }}>      {this.state.error && this.state.error.toString()}      <br />      {this.state.errorInfo.componentStack}     </details>    </div>   );  }  // Normally, just render childrenreturn this.props.children; } }class BuggyCounter extends React.Component {constructor(props) {super(props);this.state = { counter: 0 };this.handleClick = this.handleClick.bind(this); } handleClick() {this.setState(({counter}) => ({   counter: counter + 1  })); } render() {if (this.state.counter === 5) {   // Simulate a JS errorthrow new Error('I crashed!');  }return <h1 onClick={this.handleClick}>{this.state.counter}</h1>; }}function App() {return (  <div>   <p>    <b>     This is an example of error boundaries in React 16.     <br /><br />     Click on the numbers to increase the counters.     <br />     The counter is programmed to throw when it reaches 5. This simulates a JavaScript error in a component.    </b>   </p>   <hr />   <ErrorBoundary>    <p>These two counters are inside the same error boundary. If one crashes, the error boundary will replace both of them.</p>    <BuggyCounter />    <BuggyCounter />   </ErrorBoundary>   <hr />   <p>These two counters are each inside of their own error boundary. So if one crashes, the other is not affected.</p>   <ErrorBoundary><BuggyCounter /></ErrorBoundary>   <ErrorBoundary><BuggyCounter /></ErrorBoundary>  </div> );}ReactDOM.render( <App />, document.getElementById('root'));

以上就是詳解React 16 中的異常處理的資料整理,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.