You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> * Asynchronous code (e.g. `setTimeout` or `requestAnimationFrame` callbacks)
21
-
> * Server Side Rendering
22
+
> * Server side rendering
23
+
> * Errors thrown in the error boundary itself (rather than its children)
22
24
23
25
A class component becomes an error boundary if it defines a new lifecycle method called `componentDidCatch(error, info)`:
24
26
@@ -136,37 +138,42 @@ However, React components are declarative and specify *what* should be rendered:
136
138
137
139
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` hook caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
138
140
139
-
However, an event handler inside of a React component could leverage `try` / `catch` to deal with errors that occur during event handling.
React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle hooks, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
146
+
147
+
If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:
140
148
141
149
```js{8-12,16-19}
142
150
class MyComponent extends React.Component {
143
151
constructor(props) {
144
152
super(props);
145
-
this.state = { error: null }
153
+
this.state = { error: null };
146
154
}
147
155
148
156
handleClick = () => {
149
157
try {
150
-
// event handling that could possibly produces an error
151
-
} catch(error) {
152
-
this.setState({ error })
158
+
// Do something that could throw
159
+
} catch(error) {
160
+
this.setState({ error });
153
161
}
154
162
}
155
163
156
164
render() {
157
165
if (this.state.error) {
158
-
// render a fallback UI
159
-
return <h1>The Click Handler Produces an Error</h1>
Note that the above example is demonstrating regular JavaScript behavior and doesn't use error boundaries.
167
174
168
175
## Naming Changes from React 15
169
176
170
177
React 15 included a very limited support for error boundaries under a different method name: `unstable_handleError`. This method no longer works, and you will need to change it to `componentDidCatch` in your code starting from the first 16 beta release.
171
178
172
-
For this change, we’ve provided a [codemod](https://github.com/reactjs/react-codemod#error-boundaries) to automatically migrate your code.
179
+
For this change, we’ve provided a [codemod](https://github.com/reactjs/react-codemod#error-boundaries) to automatically migrate your code.
0 commit comments