Skip to content

警告: Encountered two children 使用相同键

错误信息

                Encountered two children 使用相同键, `X`. 键必须是 唯一.
              

快速摘要

Two or 更多列表项 有相同键 值, 哪个 prevents React 从正确地 identifying 哪个项 更改.

为什么发生

  • 数据项 share 相同 ID (数据 integrity issue)

  • Using 非-唯一字段 as 键 (e.g., 分类 name)

  • Concatenating 列表不使用 ensuring 键 uniqueness

最小示例

✗ 错误代码
{items.map(item => (
  <li key={item.category}>{item.name}</li>
))}
// Multiple items can have the same category!
✓ 修复代码
{items.map(item => (
  <li key={item.id}>{item.name}</li>
))}
// Use unique id instead of category

Using 唯一 id 相反的 shared 分类 ensures 每个键 是唯一, preventing React 从 confusing 项.

如何诊断

  • Log 所有键 到检查 for duplicates

  • 验证数据源 有唯一 IDs

  • 检查如果多个列表是 rendered in 相同 parent

如何修复

  • Ensure 每个项 有 truly 唯一键

  • Prefix 键: 键={${listName}-${项.id}}

  • Fix 数据源 到 provide 唯一 IDs

如何预防

  • 总是 use 唯一 IDs 从数据库 as 键

  • 当组合列表, prefix 键到 ensure uniqueness

相关资源

相关术语

相关课程

← 返回语言