国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

詳解React 16 中的異常處理

2024-05-06 16:38:43
字體:
來源:轉載
供稿:網友

詳解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 中的異常處理的資料整理,如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 四川省| 伊宁县| 太和县| 新绛县| 天门市| 台北市| 巴南区| 怀集县| 景洪市| 博客| 屏南县| 亳州市| 额敏县| 松桃| 友谊县| 铁岭市| 桐柏县| 赞皇县| 民权县| 太仓市| 宁津县| 右玉县| 新余市| 高州市| 如皋市| 邢台县| 临西县| 墨玉县| 娄底市| 海阳市| 新乡市| 汕头市| 宜春市| 文水县| 祥云县| 隆德县| 眉山市| 马尔康县| 保靖县| 永修县| 龙游县|