Skip to content

键

一句话解释

键是 特殊字符串 prop 那个唯一地 identifies 列表项, helping React match 元素跨越 re-渲染 for efficient 更新.

用大白话说

key prop is a special attribute React uses to identify which items in a list have changed. When React reconciles a list, it uses keys to match old elements to new ones. If a key exists in both the old and new list, React updates that element in place; if a key is new, React mounts a new element; if a key is gone, React unmounts the element.

Always use stable, unique keys — the best choice is a unique ID from your data (a database ID, a UUID). Avoid using array indices as keys when the list can be reordered, items can be inserted at the beginning, or items can be deleted — index-based keys cause React to incorrectly reuse DOM nodes, leading to subtle state bugs.

Keys only need to be unique among siblings, not globally. They are not passed to the component as a prop — React consumes them internally.

示例

jsx
// Good: stable unique IDs
{items.map(item => <ListItem key={item.id} item={item} />)}

// Bad: index keys (causes bugs on reorder)
{items.map((item, index) => <ListItem key={index} item={item} />)}

Using 项.id as 键是 stable and 唯一. Using 数组索引能 cause 不正确 DOM reuse 当项 move or 是移除.

常见混淆

  • 容易混淆的对象: id prop

    关键区别: 键是 React-内部 prop used for reconciliation and 是不 通过到 组件. id 是 regular HTML attribute 那个端 上 on DOM 元素. 它们 serve 不同 purposes.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表