reactjs / reactjs/react.dev

`state` property must be defined if `getDerivedStateFromProps` is used

Aberta
#796 3 comentários 10 reações 0 responsáveis Ver no GitHub

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 state for the construction to work correctly.
  • I can use this.setState without ever having initialized state without 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 that getDerivedStateFromProps was returning undefined.
  • There isn't any documentation in getDerivedStateFromProps or 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

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. 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

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.