mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-22 20:01:57 +00:00
Tweak gDSFP section
This commit is contained in:
@@ -11,17 +11,9 @@ TODO (@bvaughn)
|
||||
|
||||
## Bugfix for `getDerivedStateFromProps`
|
||||
|
||||
`getDerivedStateFromProps` is now called when either props or state change. Previously, it would not fire for state-only changes (similar to `componentWillReceiveProps`). This was an oversight in the initial implementation that has now been corrected.
|
||||
`getDerivedStateFromProps` is now called every time a component is rendered, regardless of the cause of the update. Previously, it was only called if the component was re-rendered by its parent; it would not fire as the result of a local `setState`. This was an oversight in the initial implementation that has now been corrected. The previous behavior was more similar to how `componentWillReceiveProps` works, but the improved behavior ensures compatibility with React's upcoming asynchronous rendering mode.
|
||||
|
||||
### Why?
|
||||
|
||||
`getDerivedStateFromProps` was designed as an alternative to `componentWillReceiveProps` that is compatible with async rendering. Because props in React are derived from state that lives in a parent component, APIs like `componentWillReceiveProps` that are modelled around "prop change events" don't really make sense, and can't be reliably implemented in React's upcoming asynchronous rendering mode.
|
||||
|
||||
Another way to think about it is that `getDerivedStateFromProps(props, state)` accepts both props and state as input, so we need to re-calculate the derived state whenever either of the inputs change.
|
||||
|
||||
### How Does This Affect Me?
|
||||
|
||||
**Most likely, this doesn't require any changes to your components**. The rare cases where it does matter usually fall into one of two categories:
|
||||
**Most likely, this doesn't require any changes to your components**. The rare cases where it does matter fall into one of two categories:
|
||||
|
||||
### Avoid Side Effects in `getDerivedStateFromProps`
|
||||
|
||||
@@ -31,7 +23,7 @@ Side effects in `getDerivedStateFromProps` were already disallowed, but since it
|
||||
|
||||
### Compare Incoming Props to Previous Props When Computing Controlled Values
|
||||
|
||||
The following code will not work. It assumes `getDerivedStateFromProps` only fires on prop changes. But since it now fires for state changes, too, local updates to the controlled value will be ignored, since the props version always overrides it.
|
||||
The following code assumes `getDerivedStateFromProps` only fires on prop changes. But since it now fires for state changes, too, local updates to the controlled value will be ignored, since the props version always overrides it.
|
||||
|
||||
```js
|
||||
static getDerivedStateFromProps(props, state) {
|
||||
|
||||
Reference in New Issue
Block a user