`state` property must be defined if `getDerivedStateFromProps` is used
Nessuno ha ancora preso questa issue.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
It seems that if getDerivedStateFromProps is defined, the component must also initialize its state property. That requirement is undocumented.
The following react component will generate a warning: "MyComponent: Did not properly initialize state during construction. Expected state to be an object, but it was undefined."
class MyComponent extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
return null;
}
render() {
return <span>Foo</span>
}
}
The warning can be resolved by adding state = {} either in the class definition or the constructor, or by not using getDerivedStateFromProps.
I found this warning confusing:
- since I'm not overriding the constructor, it's not obvious I'm responsible for initializing
statefor the construction to work correctly. - I can use
this.setStatewithout ever having initializedstatewithout warning, so I don't have prior expectations initializing state would be required to use it. - Since the only state handling logic for this component comes from
getDerivedStateFromProps, I confused the warning with saying thatgetDerivedStateFromPropswas returning undefined. - There isn't any documentation in
getDerivedStateFromPropsor in "State and Lifecycle" that this initialization is required if that lifecycle method is used
I don't know if this is best resolved by making the warning clearer, or documenting the requirement for state initialization either in the docs for getDerivedStateFromProps or in "State and Lifecycle". In hindsight, the warning (while perhaps a little succinct) does indicate what the problem is; it's just that the solution is non-obvious. So I figured I'd open this as a docs issue here.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia dalla documentazione di getDerivedStateFromProps e dalla sezione “State and Lifecycle” menzionata nell’issue. Conferma come viene descritta l’inizializzazione dello stato, quindi chiarisci che i componenti che utilizzano questo lifecycle devono inizializzare lo stato; completato quando il requisito e la risoluzione sono documentati nella guida pertinente.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- javascript, react
- Ambito
- documentation
- Tipo di issue
- Documentazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 45/100