react 错误边界 getDerivedStateFromError 捕获子组件的生命周期函数中的错误!
import React, { Component } from "react";
import Child from "./Child";
// 错误边界
export default class Parent extends Component {
state = {
hasError: '', // 固定写法,值为空字符串,不能写别的,不然无法达到效果
};
static getDerivedStateFromError(error) {
console.log(error)
return {
hasError: error, // 和state中hasError字段对应
};
}
render() {
return (
<div>
<h1>我是Parent组件</h1>
{this.state.hasError ? <span>网络不稳定</span> : <Child />}
</div>
);
}
}
A little hug, little gift.
All of little something.
these are our meories.