警告:遇到两个具有相同键 `duplicate` 的子元素。键应该是唯一的,以便组件在更新时保持其身份。非唯一键可能导致子元素重复和/或遗漏——此行为不受支持,并可能在将来版本中更改。
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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
当使用 .map() 渲染列表时,两个或多个项目具有相同的 key prop,违反了键在同级元素中必须唯一的要求。
English
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.
官方文档
https://reactjs.org/docs/lists-and-keys.html#keys解决方案
-
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());
无效尝试
常见但无效的做法:
-
Using the array index as the key
40% 失败
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% 失败
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% 失败
This works if item.id is unique, but if not, the concatenation may still produce duplicates. Better to use a truly unique identifier.