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

首頁 > 編程 > JavaScript > 正文

詳解React 16 中的異常處理

2019-11-19 15:57:51
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 道真| 宜宾县| 天水市| 金溪县| 许昌市| 上饶市| 辽源市| 县级市| 皋兰县| 康马县| 图木舒克市| 库尔勒市| 手游| 错那县| 诸城市| 乌拉特中旗| 浦东新区| 龙江县| 会泽县| 新乐市| 恩施市| 米泉市| 安新县| 宣恩县| 漳平市| 团风县| 平武县| 德保县| 枣阳市| 长岛县| 三都| 那曲县| 桂林市| 寻乌县| 治多县| 深泽县| 枣强县| 永平县| 轮台县| 昌平区| 叙永县|