react
runtime_error
ai_generated
true
Warning: Encountered two children with the same key, `duplicate`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
ID: react/duplicate-key-in-list
95%Fix Rate
85%Confidence
1Evidence
2023-07-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
Root Cause
When rendering a list with .map(), two or more items have the same key prop, violating the requirement that keys must be unique among siblings.
generic中文
当使用 .map() 渲染列表时,两个或多个项目具有相同的 key prop,违反了键在同级元素中必须唯一的要求。
Official Documentation
https://reactjs.org/docs/lists-and-keys.html#keysWorkarounds
-
95% success Use a unique identifier from your data as the key: data.map(item => <Component key={item.id} />). If no unique ID exists, generate one when data is created (e.g., using uuid).
Use a unique identifier from your data as the key: data.map(item => <Component key={item.id} />). If no unique ID exists, generate one when data is created (e.g., using uuid). -
85% success If the data has duplicate IDs, deduplicate the array before rendering: const uniqueData = Array.from(new Map(data.map(item => [item.id, item])).values());
If the data has duplicate IDs, deduplicate the array before rendering: const uniqueData = Array.from(new Map(data.map(item => [item.id, item])).values());
中文步骤
Use a unique identifier from your data as the key: data.map(item => <Component key={item.id} />). If no unique ID exists, generate one when data is created (e.g., using uuid).If the data has duplicate IDs, deduplicate the array before rendering: const uniqueData = Array.from(new Map(data.map(item => [item.id, item])).values());
Dead Ends
Common approaches that don't work:
-
Using the array index as the key
40% fail
While this suppresses the warning, using index as key can cause incorrect component behavior if the list order changes (e.g., sorting, filtering).
-
Generating a random key on each render (e.g., Math.random())
70% fail
Random keys cause React to remount all components on every render, losing state and causing performance degradation.
-
Concatenating index with another value (e.g., key={`${index}-${item.id}`})
30% fail
This works if item.id is unique, but if not, the concatenation may still produce duplicates. Better to use a truly unique identifier.