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

124
Visualizações
react duplicate key mechanism

I want to understand the result of this codes. I think it's related to React "keys."

const {useState} = React;

/*export default*/ function App() {
  const [alphabets, setAlpabets] = useState([
    { key: "b", name: "b2" },
    { key: "b", name: "b" },
    { key: "a", name: "a1" },
    { key: "a", name: "a2" }
  ]);
  const handleChange = () => {
    setAlpabets([{ key: "a", name: "a3" }]);
  };
  return (
    <div className="App">
      {alphabets.map(({ key, name }) => (
        <p key={key}>{name}</p>
      ))}
      <button onClick={handleChange}>change</button>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

This code renders b2, b, a1, and a2 initially, then when I trigger the change button the result is b2, a1, and a3.

I expected the result to be a3 because after triggering the button, alpabets only has key "a". Why does it have the others?

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

0

That error is normal, when you are using map to loop through a list of item in an array and use key to help react in magment of reference to each item inside of the loop the key props must be unique for each item in the map loop. In your case there are two item with the same key

{ key: "b", name: "b2" }
{ key: "b", name: "b" }

And

{ key: "a", name: "a1" }
{ key: "a", name: "a2" }

Their have the same value for the key property

To avoid to use key attribute of each object in the array you can use the index of that item like this

 return (
    <div className="App">
        {alphabets.map(({ key, name }, index) => (
            <p key={index}>{name}</p>
        ))}
        <button onClick={handleChange}>change</button>
    </div>
  );

You can read nore about Array.prototype.map

about 4 years ago · Juan Pablo Isaza Relatório

0

React keys should be unique, keys help react to track the changes happened to the item.

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

See more of List and Keys

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