React
react/no-array-index-key
A list item's key comes from the data (an id), not from the array index.
umiarkowanastatycznefe-react
Dlaczego
React matches list items between renders by key. With the index as key, inserting, removing or sorting items gives each component the state of its neighbour: typed text, checked boxes and focus move to the wrong row.
Poprawka
Use a stable id from the data: key={todo.id}. If the data has none, create ids when the data is created (crypto.randomUUID()), not during render. The index is acceptable only for a static list that never reorders and holds no state.
Przykłady
// bad
{todos.map((todo, index) => <Todo key={index} todo={todo} />)}
// good
{todos.map((todo) => <Todo key={todo.id} todo={todo} />)}Źródła
Fakty
- Identyfikator
react/no-array-index-key- Waga
- umiarkowana
- Sprawdzanie
- statyczne sprawdzane w kodzie źródłowym przez
audit - Dotyczy plików
jsx- Tylko w projektach z
reactnextpreact- Uczy jej skill
fe-reactReact components- Od wersji
- 0.1.0
Przeczytaj w terminalu
npx github:dawidolko/frontend-skills explain react/no-array-index-key