# 警告：遇到两个具有相同键 `duplicate` 的子元素。键应该是唯一的，以便组件在更新时保持其身份。非唯一键可能导致子元素重复和/或遗漏——此行为不受支持，并可能在将来版本中更改。

- **ID:** `react/duplicate-key-in-list`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 95%

## 根因

当使用 .map() 渲染列表时，两个或多个项目具有相同的 key prop，违反了键在同级元素中必须唯一的要求。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8+ | active | — | — |
| React 17.0.2 | active | — | — |
| React 18.2.0 | active | — | — |

## 解决方案

1. ```
   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).
   ```
2. ```
   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** — While this suppresses the warning, using index as key can cause incorrect component behavior if the list order changes (e.g., sorting, filtering). (40% 失败率)
- **Generating a random key on each render (e.g., Math.random())** — Random keys cause React to remount all components on every render, losing state and causing performance degradation. (70% 失败率)
- **Concatenating index with another value (e.g., key={`${index}-${item.id}`})** — This works if item.id is unique, but if not, the concatenation may still produce duplicates. Better to use a truly unique identifier. (30% 失败率)
