errorBoundary错误边界

本文最后更新于:2 年前

理解:

错误边界:用来捕获后代组件错误,渲染出备用页面

子组件出现错误,导致组件不可控,出现穿透影响其他组件显示
image.png

特点:

只能捕获后代组件生命周期产生的错误,比如render里产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误

解决:

在父组件中设置getDerivedStateFromError,当后代组件出现错误时,getDerivedStateFromError就会触发,并且携带错误信息。(常常调用API中的数据时会出错)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React,{Component} from 'react';
import Children from './children';

class Parent extends Component {
state = {hasError:''}

// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
console.log(error);
// 在render之前触发
// 返回新的state
return { hasError: true };
}
render(){
return (
<div>
<h3>我是Parent组件</h3>
{this.state.hasError ? <h5>请求繁忙,请稍后再试...</h5> : <Children />}
</div>
)
}
}


使用方法

getDerivedStateFromError配合componentDidCatch使用,componentDidCatch是出现错误时执行,一般用于统计并记录错误的信息

1
2
3
4
5
6
7
8
9
10
11
12
13
// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
console.log(error);
// 在render之前触发
// 返回新的state
return {hasError: true};
}

componentDidCatch(error, info) {
// 统计页面的错误,发送请求发送到后台去
console.log(error, info);
}