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>
);
}
}