React 错误处理(componentDidCatch)

前言

   看react 文档突然发现有这个 错误处理函数,好像是17年9月出的,这个真的绝了可以帮助我们捕捉错误咯

 

 React 16 将提供一个内置函数 componentDidCatch,如果 render() 函数抛出错误,则会触发该函数。

官网例子

下面这个:

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 是包含错误堆栈的 info 对象!

{this.state.info && this.state.info.componentStack}

 

当然我是这么用的在路由那边

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      hasError: false
    }
  }
  componentDidCatch(error, info) {
    console.log(error, info)
    this.setState({
      hasError: true
    })
  }
  render() {
    return this.state.hasError ?
      <h2>页面出错了404</h2>
      : (
        <React.Fragment>
          {/* 检验是否有登录信息 */}
          <AutoRoute />
          {/* 有了switch后,匹配到path后就不会再匹配下去了 */}
          <Switch>
            <Route path="/login" component={Login}></Route>
            <Route path='/register' component={Register}></Route>
            <Route path='/chat/:user' component={Chat}></Route>
          </Switch>
        </React.Fragment>
      )
  }
}

其实还是组件化比较好一点,毕竟复用性比较高

转载于:https://www.cnblogs.com/yf-html/p/9294737.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值