React 之 错误边界

默认情况下,若一个组件在渲染期间(render)发生错误,会导致整个组件树全部被卸载

错误边界:是一个组件,该组件会捕获到渲染期间(render)子组件发生的错误,并有能力阻止错误继续传播


组件中添加捕获错误

1.编写生命周期函数 getDerivedStateFromError

1.该函数为静态函数 static getDerivedStateFromError

2.运行时间点:子组件被渲染发生错误之后且也页面更新之前

3.只有子组件发生错误时,该函数才会被执行

4.该函数返回一个对象,React会将该对象的属性覆盖掉当前组件的state

5.参数:错误对象

6.通常该函数用于改变状态值

class ErrorBound extends React.Component {
    this.sate={
        hasError:false
    }
   //   该函数为静态函数
    static getDerivedStateFromError(error){
        console.log(error)
        return {     // 返回的值会自动 调用setState,将值和state合并
            hasError:true
        }
    }
    render(){
        if(this.state.hasError){
            return null
        }
        return this.props.children
    }
}
​
function Comp1 (){
    return(
          <div
            style={{ width: "500px", height: "500px", border: "1px solid red" }}
          >
            <h1>Comp1</h1>
            <Comp2 />
          </div>
    )
}


2.编写生命周期函数 componentDidCatch

1.实例方法

2.运行时间点:子组件渲染发生错误且页面更新之后;由于该函数的运行时间点比较靠后,因此不会在该函数中改变状态

3.通常该函数用于记录错误信息

class ErrorBound extends React.Component {
    this.sate={
        hasError:false
    }
​
componentDidCatch(error,info){
    console.log(error)
    consoel.log(info)
    this.setState({
        hasError:true
    })
}
​
    render(){
        if(this.state.hasError){
            return null
        }
        return this.props.children
    }
}
​
function Comp1 (){....}


细节

某些错误,错误边界组件无法捕获

1.组件的自身错误

2.异步错误,比如计时器

3.事件中的错误,比如click事件中发生的错误

总结:仅处理渲染子组件的同步错误
class ErrorBound extends Component {
  render() {
    return (
      <div>
        <Comp1 />
        <Comp3 />
      </div>
    );
  }
}
​
class Comp1 extends Component {
  state = {
    hasError: false
  };
​
  static getDerivedStateFromError(e) {
    console.log(e);
    return {
      hasError: true
    };
  }
​
   componentDidMount() {
     setTimeout(() => {
         throw Error("ERR");
       }, 1000);
     }
​
  render() {
       throw Error("ERR");
    return (
      <div>
        {this.state.hasError ? null : (
          <div
            style={{ width: "500px", height: "500px", border: "1px solid red" }}
          >
            <h1
              onClick={() => {
                throw Error("ERR");
              }}
            >
              Comp1
            </h1>
            <Comp2 />
          </div>
        )}
      </div>
    );
  }
}

发布于 2020-01-19 19:29