標籤:

React 16 中的異常處理

React 16 中的異常處理翻譯自 React 官方文檔,從屬於筆者的 React 與前端工程化實踐系列中的 React 組件分割與解耦章節;也可以使用 create-webpack-app 運行本部分示例 。

異常處理

在 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 stylex={{ 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"));

推薦閱讀:

基於 Webpack 的應用包體尺寸優化
React 實現一個漂亮的 Table
React Conf 2017 不能錯過的大起底——Day 1!
解析 Redux 源碼
我對Flexbox布局模式的理解

TAG:Web开发 | React |