警告: 每个 child in 列表应该有 唯一键 prop
错误信息
每个 child in 列表应该有 唯一键 prop
快速摘要
你 rendered 列表的 元素不使用 providing 唯一 `键` prop 到每个项, 哪个 prevents React 从 efficiently tracking 项.
为什么发生
Forgot 到添加
键prop 当 using.映射()Used 数组索引 as 键使用动态列表
键是 不唯一跨越 siblings
最小示例
✗ 错误代码
{items.map(item => (
<li>{item.name}</li> // No key!
))}✓ 修复代码
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}添加 键={项.id} gives React stable identity for 每个项, 启用 efficient reconciliation and preventing 状态 bugs.
如何诊断
Look for
.映射()calls in 组件那个返回 JSX 不使用键检查那个每个键 是唯一其中 siblings
验证键 是 stable (don't 更改之间渲染)
如何修复
添加唯一
键prop 到每个列表项:键={项.id}Use stable 唯一 ID 从你的数据 as 键
如果否 ID exists, 组合多个字段到 创建唯一键
如何预防
总是包含唯一 ID 字段 in 你的数据 models
从不 use 数组索引 as 键 for 动态列表