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
.
As you already mentioned in your question that pressing Esc
cancels the overlay and you can see the ErrorBoundary
message and the visibility of the overlay is limited to development environment.
You can check more about it here
However as to why the render function is executing, you need to know that once the render
function is executed and there is a RuntimeError that is being thrown by your code, is the only time that componentDidCatch
method of your ErrorBoundary
. Also create-react-app
has a functionality whereby it listens to the RuntimeErrors
that are being produced and it reports the root cause of the Error which is what you see in the overlay.
To check the relevant code that produces the Overlay, you can check this github code
I hope I am able to answer your question.