I use React 16
with Error Boundary
functionality:
Profile.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>
}
}
I saw the functional component is still called after the error happened and has been caught. Can anyone please explain why the render
function is called.
For someone doesn't know, follow the answer from link, you can see the error boundary by press the key esc
.