react -- 错误边界

用途:

错误边界:用于解决部分 UI 的 JavaScript 错误不应该导致整个应用崩溃的问题

注意

错误边界无法捕获以下场景中产生的错误:

  • 事件处理(了解更多
  • 异步代码(例如 setTimeoutrequestAnimationFrame 回调函数)
  • 服务端渲染
  • 它自身抛出来的错误(并非它的子组件)

如果一个 class 组件中定义了 static getDerivedStateFromError() 或 componentDidCatch() 这两个生命周期方法中的任意一个(或两个)时,那么它就变成一个错误边界。当抛出错误后,请使用 static getDerivedStateFromError() 渲染备用 UI ,使用 componentDidCatch() 打印错误信息。

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // 你同样可以将错误日志上报给服务器
    logErrorToMyService(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // 你可以自定义降级后的 UI 并渲染
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}

然后你可以将它作为一个常规组件去使用:

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

使用的实现:

// 错误边界: ErrorBoundary.js文件
import React, { Component } from "react"

class ErrorBoundary extends Component {
    constructor(props) {
        super(props)
        this.state = {
            hasError: false,
        }
    }

    static getDerivedStateFromError(error) {
        return { hasError: true }
    }

    componentDidCatch(error, errorInfo) {
        console.log(error, errorInfo)
    }

    render() {
        if (this.state.hasError) {
            return <h1>出现错误,显示边界内容</h1>
        }
        return this.props.children
    }
}

export default ErrorBoundary
// 出现错误文件:BuggyCounter 
import React, { Component } from "react"

class BuggyCounter extends 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) {
            throw new Error('I crashed!')
        }
        return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
    }
}

export default BuggyCounter

页面中显示使用

		<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>

页面效果:
在这里插入图片描述
当点击数字时,数字增加1,知道等于5时报错,显示错误边界内容
在这里插入图片描述
从点击效果可以看出,第一个块的两个 <BuggyCounter /> 使用同一个 ErrorBoundary 错误边界组件包裹,当其中一个 <BuggyCounter /> 发生错误时,整个块内容都由错误边界的内容替换。即使用ErrorBoundary错误边界组件包裹的任何内容产生错误,整个ErrorBoundary内的内容都将替换。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值