反应:使用索引作为列表中项目的键 [英] React: using index as key for items in the list

查看:44
本文介绍了反应:使用索引作为列表中项目的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用索引作为列表中项目的键有哪些陷阱?在添加或删除列表中的元素时,是否存在 React 更改检测或任何意外列表更新的性能缺陷.我已经阅读了几篇关于此的文章,但仍然没有弄清楚.

What are the pitfalls of using an index as key for items in the list? Is there any performance pitfall for React change detection or any unexpected list update while adding or removing elements in the list as well. I have gone through several articles regarding this but still not getting it clear.

请参考codepen

为什么在列表的开头添加一个项目会导致上述 codepen 出现意外行为?

Why adding an item at the start of the list result in unexpected behavior in the above codepen?

另外,据说当没有键传递时,默认情况下react将索引作为键传递.这意味着不传递任何键和传递索引作为键 - 两者是一回事吗?

Also, it is said that by default react passes index as a key when no key is passed. That means not passing any key and passing index as a key - both are the same thing?

推荐答案

这个问题以前有人问过,

this question has been asked before,

但主要答案可以在 React 文档

如果项目的顺序可能会影响,我们不建议对键使用索引改变.这会对性能产生负面影响,并可能导致问题带组件状态.查看 Robin Pokorny 的文章深入解释使用指数作为指标的负面影响钥匙.如果您选择不为列表项分配显式键,则React 将默认使用索引作为键.

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

添加或删除元素时没有意外的列表更新

there are no unexpected list update while adding or removing elements

但造成这种情况的主要原因是后面的索引和比较算法,

but the main reason for this is the algorithm for indexing and comparing behind,

您可以在此处在不同-类型'

you can read about this here under 'different-types'

这里的关键是要了解并非 DOM 中的所有内容都在 ReactVirtual DOM"中具有表示形式,并且因为对 DOM 的直接操作(例如用户更改值或侦听元素的 jQuery 插件)不会被React,不使用唯一和常量键将导致当键不是常量时 React 重新创建组件的 DOM 节点(并丢失节点中的任何未跟踪状态),或者当键不是时重用 DOM 节点来渲染另一个组件唯一(并将其状态绑定到另一个组件).

The key here is to understand not everything in the DOM has a representation in React "Virtual DOM" and, because direct manipulations of the DOM (like a user changing an value or a jQuery plugin listening to an element) are unnoticed by React, not using unique and constant keys will end up with React recreating the DOM node of a component when the key is not constant (and losing any untracked state in the node) or reusing a DOM node to render another component when the key is not unique (and tying its state to this other component).

这里你有一个现场演示,展示了结果有多糟糕

Here you have a live demo showing how awful the results are

只需添加一个项目,更改它,添加更多项目,然后看看会发生什么.

Just add an item, change it, add more items and see what happens.

阅读这里

这篇关于反应:使用索引作为列表中项目的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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