It is a myth and misunderstanding the key={...} make the display correct
还没有人认领这个 Issue。
- 主要语言
- JavaScript
- 星标
- 11.8k
- 派生
- 7.9k
- 平均合并
- 1 天 11 小时
- 30 天内合并 PR
- 11
描述
On page https://react.dev/learn/rendering-lists
it is said that:
A well-chosen key helps React infer what exactly has happened, and make the correct updates to the DOM tree.
That's a myth that the key keeps the updates correct. It helps to make the update faster, so that it goes by row level diff'ing, instead of cell level diff'ing.
For example, if you have a table with 5 fields. They key can make it so that the diff'ing happens with the prev row, so that it is faster.
Imagine if row 23 supposedly needed to compare with row 24, due to row added or deleted, but due to the key being bad, it is compared to row 23, and all the fields are different, so React needs to update it cell by cell.
If the key is good, however, now row 23 will be compared with row 24, and nothing changes, and no update is needed whatsoever.
You can check with an advanced engineer about this. The myth about "you need a good key so that the displayed data is correct", is wrong.
Maybe the original line "make the correct updates to the DOM tree" doesn't suggest that, but it can make readers think this way. So you may want to rephrase it or further explain it.
So this part later in the page:
You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.
is also a wrong concept. It will NOT lead to subtle and confusing bugs. It will just make it slow, but the display will still all be correct.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先阅读 https://react.dev/learn/rendering-lists 上的 Rendering Lists 页面,包括关于 key 和数组索引的引用部分。根据 React 记录的行为验证这些说法,并确定措辞是否需要澄清;完成的标准是该页面上体现了一份达成共识且技术上准确的解释。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript, react
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100