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?
CodePudding user response:
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
CodePudding user response:
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