错误:不要在键中使用数组索引 [英] error: Do not use Array index in keys

查看:39
本文介绍了错误:不要在键中使用数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用索引在列表中生成键.但是,es-lint 会产生相同的错误.React doc 还指出使用项目索引作为键应该作为最后使用采取.

I am using index to generate key in a list. However, es-lint generates an error for the same. React doc also states that using the item index as a key should be used as last resort.

const list = children.map((child, index) =>
    <li key={index}> {child} </li>);

我考虑过使用 react-key-index.npm install react-key-index 给出以下错误:

I considered using react-key-index. npm install react-key-index gives following error:

npm 错误!代码 E404

npm 错误!404 未找到:react-key-index@latest

对其他允许生成唯一密钥的软件包有什么建议吗?对反应密钥生成器的任何建议表示赞赏!

Are there any suggestions on other packages that allow to generate unique key? Any suggestion on react key generator is appreciated!

推荐答案

当您使用数组的索引作为键时,React 将进行优化而不是按预期呈现.在这种情况下会发生什么可以用一个例子来解释.

When you use index of an array as a key, React will optimize and not render as expected. What happens in such a scenario can be explained with an example.

假设父组件获取一个包含 10 个项目的数组,并根据该数组渲染 10 个组件.假设然后从数组中删除第 5 项.在下一次渲染时,父级将收到一个包含 9 个项目的数组,因此 React 将渲染 9 个组件.这将显示为第 10 个组件被移除,而不是第 5 个,因为 React 无法根据索引区分项目.

Suppose the parent component gets an array of 10 items and renders 10 components based on the array. Suppose the 5th item is then removed from the array. On the next render the parent will receive an array of 9 items and so React will render 9 components. This will show up as the 10th component getting removed, instead of the 5th, because React has no way of differentiating between the items based on index.

因此,对于从项目数组呈现的组件,始终使用唯一标识符作为键.

Therefore always use a unique identifier as a key for components that are rendered from an array of items.

您可以使用唯一的子对象的任何字段作为键来生成自己的唯一键.正常,子对象的任何id字段都可以使用.

You can generate your own unique key by using any of the field of the child object that is unique as a key. Normal, any id field of the child object can be used if available.

如果组件创建和管理自己的状态,您将只能看到上述行为发生,例如在不受控制的文本框、计时器等中.移除输入组件时反应错误

Edit : You will only be able to see the behavior mentioned above happen if the components create and manage their own state, e.g. in uncontrolled textboxes, timers etc. E.g. React error when removing input component

这篇关于错误:不要在键中使用数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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