react异常捕获处理、边界处理

最近项目全面转向react,写了两个项目后发现render里面的异常无法捕获,就无法监控上报错误信息等,后来想了想这么强大的react,肯定会有处理方法。
  • 部分UI的异常,不能破坏了整个页面,在 React 16+引入了一种称为“错误边界”的新概念。错误处理指的是React组件中能捕获子组件树中的任何Javascript异常,打印出来,并且展示出备用UI的生命周期方法 从而避免了组件树崩溃。它能在整个渲染及构建dom树的过程中捕获异常。
  • react就定义了一个新的生命周期,主要是捕获render的异常处理
componentDidCatch(error, errorInfo)

第一个参数是实际抛出的错误,第二个参数是指错误信息。componentDidCatch生命类似于try/catch 语句,它不能捕获本省的错误的错误,而是将错误传给离它最近的异常上。

  • componentDidCatch究竟做了什么,有什么好处?
    1、当有错误发生时, 我们可以友好地展示 fallback 组件;
    2、可以捕捉到它的子元素(包括嵌套子元素)抛出的异常;
    3、可以复用错误组件;
    4、不能捕获时间的异常、定时器等
  • 接下来,来看具体的例子,这是简单封装的一个异常捕获的组件
import React, {Component} from 'react';

class ErrCapture extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }
    logErrorToMyService(error){
        const {abnormalLog}=this.props
        if(abnormalLog){
            abnormalLog(error) //像服务器上报的错误信息
        }
    }
    componentDidCatch(error, info) {
        this.setState({ hasError: true });
        this.logErrorToMyService(error, info);
    }
    render() {
        const {ErrComponent,abnormalLog}=this.props
        if (this.state.hasError) {
            return <h1>
                Something went wrong
                <ErrComponent/>
            </h1>;
        }
        return this.props.children;
    }
}
export default ErrCapture;

具体调用上面捕获异常组件的方法,componentDidCatch()方法可以帮我们捕捉到Login的错误信息了

import React, {Component} from 'react';
import ErrCapture from '../pages/Home'
import Login from '../components/Login'
class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: ''
        }
    }
    render() {
        return (
            <div className="cf">
                <ErrCapture ErrComponent={Code} abnormalLog={(e11)=> log.LoginError(e11)}>
                    <Login/>
                </ErrCapture>
              
            </div>
        )
    }
}

export default Index;

你可能感兴趣的:(study)