`state` property must be defined if `getDerivedStateFromProps` is used
Ninguém assumiu esta issue ainda.
- Linguagem predominante
- JavaScript
- Estrelas
- 11.8k
- Forks
- 7.9k
- Merge médio
- 1d 11h
- PRs com merge (30d)
- 11
Descrição
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.
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Direção de pesquisa
Comece pela documentação de getDerivedStateFromProps e pela seção “State and Lifecycle” mencionada na issue. Confirme como a inicialização do estado é descrita e, em seguida, esclareça que os componentes que usam este lifecycle devem inicializar o estado; concluído quando o requisito e a resolução estiverem documentados na orientação relevante.
Escrita pelo modelo de indexação a partir do texto da issue.
Avaliação
- Stack de tecnologia
- javascript, react
- Domínio
- documentation
- Tipo de issue
- Documentação
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Status de atividade
- Estagnada
- Clareza
- Razoavelmente clara
- Facilidade para iniciantes
- 45/100