在React中映射时,在数组中设置ID变量与使用索引之间是否存在差异?
我知道,在React中映射数组时,我不应将索引用作键。 共识似乎是将特定于该索引的东西用作钥匙。我的问题是您通常使用什么?做这样的事情更好,还是在映射时仅使用索引没有什么不同?
const usersWithId = users.results.map((user, index) => {
return (
{...user, id: index}
)
})
{usersWithId.map((user) => {
return (
<p key={user.id}>{user.id}</p>
)
})}
VS只是与索引一起使用
{users.map((user, index) => {
return (
<p key={index}>{user.id}</p>
)
})}
I am aware that I should not use the index as a key when mapping an array in react.
Consensus seems to be to use something particular to that index as a key. My question is what do you normally use? Is it better to do something like this or is it no different to just using the index when you are mapping?
const usersWithId = users.results.map((user, index) => {
return (
{...user, id: index}
)
})
{usersWithId.map((user) => {
return (
<p key={user.id}>{user.id}</p>
)
})}
vs just using it with the index
{users.map((user, index) => {
return (
<p key={index}>{user.id}</p>
)
})}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些密钥有助于做出反应以识别WICH元素已更改,添加了O o删除并给出元素为“身份”。选择钥匙的最佳方法是使用独特的值,该值在数组中唯一标识一个元素,并且通常是使用数据中的ID。
使用索引作为密钥是您必须使用的最后一个资源,您必须确保数组中的项目顺序不会更改。
本文真的很好:
https://robinpokorny.medium.com/index-as-a-key-is-is-is-an-an-an-pattern-e0349aece318
The keys helps to react to identify wich elements have changed, have been added o removed and give to the element a "identity". The best way to pick a key is use a unique value that uniquely identifies one element among the others in the array, and is most often to use IDs from the data.
Use the index as key is the last resource you have to use and you have to be sure that the order of items in the array will not change.
This article is really good:
https://robinpokorny.medium.com/index-as-a-key-is-an-anti-pattern-e0349aece318