我将 React 16
与 Error Boundary
功能结合使用:
配置文件.js
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
// user: {
// name: "Ha (Huck) H.K. NGUYEN"
// }
user: null
};
this.updateUser = this.updateUser.bind(this);
}
updateUser() {
this.setState({ user: null })
}
render() {
const { user } = this.state;
console.log(user);
return <div className="App">
{user.name}
<button onClick={this.updateUser}>
Update
</button>
</div>
}
}
ErrorBoundary.js
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
}
}
componentDidCatch(error, errorInfo) {
this.setState({ hasError: true });
}
render() {
const { children } = this.props;
const { hasError } = this.state;
if (hasError) {
return <HasError />
}
return children
}
}
App.js
class App extends Component {
render() {
return <div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<ErrorBoundary>
<Profile />
</ErrorBoundary>
</div>
}
}
我看到功能组件在错误发生后仍然被调用并被捕获。任何人都可以解释为什么调用 render
函数。
不知道的可以看link的回答,您可以通过按 esc
键查看错误边界。
最佳答案
正如您在问题中提到的那样,按 Esc
取消覆盖,你可以看到 ErrorBoundary
消息和覆盖层的可见性仅限于开发环境。
您可以查看更多相关信息 here
至于render函数为什么执行,你要知道一旦render
函数被执行并且您的代码抛出一个 RuntimeError,这是唯一一次 componentDidCatch
你的方法ErrorBoundary
.还有 create-react-app
具有监听 RuntimeErrors
的功能正在生成并报告错误的根本原因,这就是您在叠加层中看到的内容。
要查看产生Overlay的相关代码,可以查看这个 github code
我希望我能回答你的问题。
关于reactjs - 为什么 React 仍然渲染带有 Error Boundary 的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471005/