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

88
Visualizações
Functional component not re-rendering on state change

I'm looking to re-render a specific portion of this component, (within the .map of my JSX), depending on which value of my optionObject is set to true.

Any ideas as to where I'm going wrong would be greatly appreciated-- still kinda new to React/functional components.

  const [optionObject, setOptionObject] = useState(
    {
      'one' : false,
      'two' : false,
      'three' : true,
    }
  )

  function switchOption(selectedOption) {
    var objectCopy = optionObject;
    for (const [key, value] of Object.entries(objectCopy)) {
      if (key !== selectedOption) {
        objectCopy[key] = false;
      }
      else {
        objectCopy[key] = true;
      }
    }
    setOptionObject(objectCopy);
  }

  return (
     <>
      <div className={styles.browseOptions}>
      <div onClick={()=>switchOption(1)} className={`${styles.option} ${optionObject['one'] ? styles.active : ''}`}><h3>One</h3></div>
      <div onClick={()=>switchOption(2)} className={`${styles.option} ${optionObject['two'] ? styles.active : ''}`}><h3>Two</h3></div>
      <div onClick={()=>switchOption(3)} className={`${styles.option} ${optionObject['three] ? styles.active : ''}`}><h3>Three</h3></div>

      {multi_grid_tiles_data?.map((grid, i) => {
        if (optionObject[grid['parent']['name']])
          return (
            <div key={"gridList-"+i}>
            <GridList grid_data={grid_data}/>
           </div>
          );
      })}
     </>
  );
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

change

var objectCopy = optionObject;

to

var objectCopy = {...optionObject};

As the former doesn't copy an object, it just points to the existing object reference, therefore its the same object. The latter creates a new object reference and spreads the old contents into it.

In order for your component to rerender based on objects being updated in state, it has to be a new object reference. (same for arrays)

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