当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解React 16 中的异常处理

详解React 16 中的异常处理

2017年12月12日  | 移动技术网IT编程  | 我要评论

详解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 ui
this.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 ui
return <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 message
this.setstate({
   error: error,
   errorinfo: errorinfo
  })
  // you can also log error messages to an error reporting service here
 }

 render() {
if (this.state.errorinfo) {
   // error path
return (
    <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 children
return 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 error
throw 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 中的异常处理的资料整理,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网