Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
How to properly return updated state when using getDerivedStateFromProps lifecycle method?

For example we have such state:

state = { hasSomething: true, anotherKey: '', ... }

and we should update only 'hasSomething':

static getDerivedStateFromProps(nextProps) {
        if (nextProps.accessKey === 'admin') {
            return {
                hasSomething: false,
            };
        }
        return null;
    }

do we need to destruct the prevState when we return new state? for example like this:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.accessKey === 'admin') {
        return {
            ...prevState,
            hasSomething: false,
        };
    }
    return null;
}

or we don't need it? i checked the console.log(this.state) and it returns the whole local state if im not make a prevState destructing.

i can't find this information in official react documentation :(

P.S. this logic just an example :)

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The official documentation says It should return an object to update the state, or null to update nothing. (https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops). It is not cleared the state when you return only part of it, so it works like setState (https://reactjs.org/docs/react-component.html#setstate). The setState documentation says You may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of stateChange into the new state., so you don't need to destruct the previous state.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda