`state` property must be defined if `getDerivedStateFromProps` is used
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- JavaScript
- Sterne
- 11.8k
- Forks
- 7.9k
- Ø Merge
- 1 T. 11 Std.
- Gemergte PRs (30 T.)
- 11
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginnen Sie mit der Dokumentation zu getDerivedStateFromProps und dem im Issue erwähnten Abschnitt „State and Lifecycle“. Bestätigen Sie, wie die Zustandsinitialisierung beschrieben wird, und stellen Sie dann klar, dass Komponenten, die diesen Lifecycle verwenden, den Zustand initialisieren müssen; abgeschlossen, wenn die Anforderung und die Lösung in der relevanten Anleitung dokumentiert sind.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- javascript, react
- Bereich
- documentation
- Issue-Typ
- Dokumentation
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100