理解:
错误边界(Error boundary
):用来捕获后代组件错误,渲染出备用页面
特点:
只能捕获后代组件生命周期产生的错误,不能捕获自己组件产生的错误和其他组件在合成事件、定时器中产生的错误
使用方式:
getDerivedStateFromError
配合componentDidCatch
// 生命周期函数,一旦后台组件报错,就会触发
static getDerivedStateFromError(error) {
console.log(error);
// 在render之前触发
// 返回新的state
return {
hasError: true,
};
}
componentDidCatch(error, info) {
// 统计页面的错误。发送请求发送到后台去
console.log(error, info);
}
Demo代码:
import React, { Component } from 'react'
export default class A extends Component {
state = {error: ''}
// 父组件通过此方法捕获发生的错误
static getDerivedStateFromError(error) {
// 发生错误后,会将错误返回
return {error}
}
// 还可以使用此钩子,统计发生的错误
componentDidCatch() {
console.log('发生错误!')
}
render() {
return (
<div>
{/* 根据是否发生错误,区别显示 */}
{this.state.error ? <h1>发生错误</h1> : <B/>}
</div>
)
}
}
class B extends Component {
state = {msg: ''}
render() {
return (
<div>
{this.state.msg()} {/* 此处发生错误 */}
</div>
)
}
}
注:ErrorBoundary
在开发模式不能体现出效果,需要打包之后查看