警告:列表中的每个子元素都应该有一个唯一的'key'属性。
Warning: Each child in a list should have a unique 'key' prop. See https://reactjs.org/link/warning-keys for more information.
ID: react/missing-key-props
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.0.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 18.2.0 | active | — | — | — |
根因分析
渲染数组中的组件或元素时没有为每个项目指定唯一的 'key' 属性,这会影响 React 的协调过程并可能导致渲染错误。
English
Rendering an array of components or elements without specifying a unique 'key' prop for each item, which hinders React's reconciliation and can cause rendering bugs.
官方文档
https://reactjs.org/docs/lists-and-keys.html#keys解决方案
-
Provide a stable, unique identifier from your data as the key, e.g., `data.map(item => <Component key={item.id} />)`. If no ID exists, generate a unique key using a library like `uuid`. -
If the list is static and never reordered, use the index as a last resort with a comment documenting the limitation: `data.map((item, index) => <Component key={index} />)`
无效尝试
常见但无效的做法:
-
70% 失败
Index-based keys are unstable if the list can be reordered, filtered, or have items added/removed, leading to incorrect component state and performance issues.
-
95% 失败
Random keys cause React to unmount and remount all components on every render, destroying state and causing severe performance degradation.
-
90% 失败
Duplicate keys violate the uniqueness requirement and cause React to reuse components incorrectly, leading to unpredictable UI behavior.