在React中映射时,在数组中设置ID变量与使用索引之间是否存在差异?

发布于 2025-02-12 10:09:59 字数 523 浏览 1 评论 0原文

我知道,在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千寻… 2025-02-19 10:09:59

这些密钥有助于做出反应以识别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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文