React.js中组件键的重要性 [英] The importance of component keys in React.js

查看:82
本文介绍了React.js中组件键的重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读上的文章时感到很奇怪https://coderwall.com/p/jdybeq/the-importance-of-component-keys-in-react-js

它有一个简单的小提琴代码,它说 - 如果你没有唯一的常量键,你可能最终会进入

It has a simple fiddle code which says - If you dont have unique constant keys you might end up in


  1. 当关键时重新创建组件的DOM节点不是常数

  2. 当密钥不唯一时,重用DOM节点渲染另一个组件

它在下面容易引起混淆 -

Its quite confusing in below cased -


  1. 为什么我给key = index(即使它的唯一和常量为什么反应表现得很奇怪?)

  2. 当密钥是唯一的但不是常量时会发生什么?(如果不是只删除它,它是否检查DOM中是否存在密钥。)


推荐答案

扩展@Deadfish答案。假设你有10个待办事项,每个项目都有状态(例如是否处于编辑模式)。

Expanding on the @Deadfish answer. Let's say you have 10 todo items, and each item has state (e.g. whether it is in editing mode).

在下一个渲染过程中,只有9个待办事项剩下。例如。因为你删除了其中一个项目。

On the next render pass, there are only 9 todo items left. E.g. because you deleted one of the items.

现在需要知道还剩下哪10个原始项目,所以它可以保留每个项目的状态,然后重新开始 - 只更改状态改变的项目。

Now react needs to know which of the original 10 items are still left, so it can preserve the state of each item, and re-render only items that changed state.

这就是使用的反应。如果使用索引作为键,则原始键为0..9。并且新密钥是0..8。

That is what react uses the key for. If you use the index as the key, then the original keys were 0..9. And the new keys are 0..8.

这可能会导致一些问题:

This can cause several problems:


  1. React总会断定您删除了列表中的最后一项,这不一定正确。关于此,还有其他帖子,例如这一个

  2. React总是会断定这些项目没有改变顺序,所以反应会认为原始项目的任何状态都没有5仍将是第5项的状态。但是如果你删除了例如。编号。 3,然后所有项目都应该在列表中向上移动。这是另一个答案所指出的。

  3. 如果列表中的项目没有任何状态(只有道具) - 例如你的待办事项的标题 - 然后你的渲染将变得非常低效。如果你删除第一个项目,那么react会断定所有项目现在都有一个新文本,并将重新渲染所有剩余的项目(而不是有效地删除DOM中的第一个项目)。

使用唯一和常量键 - 在单个渲染运行中不仅仅是唯一,尤其是常量 over 多个渲染周期 - 将确保一切按预期工作,并确保有效地响应更新DOM。

Using unique and constant keys - so not just unique in a single render run, but especially constant over multiple render-cycles - will ensure that everything works as intended, and will ensure react updates DOM efficiently.

这篇关于React.js中组件键的重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆