React warning: Each child in a list should have a unique "key" prop
posée 5 months ago649 vuesen
{todos.map((t, i) => <TodoItem todo={t} />)}
I get the key warning. If I use key={i} it goes away. Is the index OK as a key?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
React uses key to match list items between renders. Use a stable, unique id from your data:
{todos.map(t => <TodoItem key={t.id} todo={t} />)}
The index is only safe if the list is never reordered, filtered, or inserted into. Otherwise React reuses the wrong component instance, and you get bugs like an input keeping the text of the item that was deleted.
If your items have no id, generate one when you *create* the item (crypto.randomUUID()), not during render.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.