简体   繁体   English

如何在 React 中为兄弟姐妹提供不变的唯一密钥

[英]How to give non-changing unique key to siblings in React

I've been struggling for over an hour but couldn't find the solution.我已经挣扎了一个多小时,但找不到解决方案。

The data structure is like数据结构就像

const arr = [
  { id: 1, title: 'something', tags: ['first', 'second', 'third'] },
  { id: 2, title: 'something', tags: ['first', 'second', 'third'] },
  { id: 3, title: 'something', tags: ['first', 'second', 'third'] },
];

And I wanna render Tag components for each item of arr using map function, like below.我想使用map function 为arr的每个项目呈现Tag组件,如下所示。

const Item = ({ item }) => (
  <article>
    <h1>{item.title}</h1>
    <ul>
      {item.tags.map(tag => (
        <Tag key={?} tag={tag} />
      ))}
    </ul>
  </article>
);

But what can I use for key except the index in an array?但是除了数组中的索引,我还能用什么作为key呢?

I tried Date.now() but it's not unique for sibling nodes, and I also tried Math.random() and it worked, but it will change every time Item re-renders.我试过Date.now()但它不是兄弟节点唯一的,我也试过Math.random()并且它有效,但它会在每次Item重新渲染时改变。 There are some libraries for this as far as I know but I heard they change too when re-rendering.据我所知,有一些库用于此,但我听说它们在重新渲染时也会发生变化。

But what can I use for key except the index in an array?但是除了数组中的索引,我还能用什么作为键呢?

For the items ( article instances), you'd use their id .对于项目( article实例),您将使用它们的id (I assume those are unique in the array.) (我假设它们在数组中是唯一的。)

For the tags, use the tag itself.对于标签,请使用标签本身。 (I'm inferring from the name "tag" that you don't have the same tag repeated in the same array.) (我从名称“标签”推断您没有在同一数组中重复相同的标签。)

const Item = ({ item }) => (
  <article key={item.id}>
  {/*      ^^^^^^^^^^^^^ */}
    <h1>{item.title}</h1>
    <ul>
      {item.tags.map(tag => (
        <Tag key={tag} tag={tag} />
        {/*  ^^^^^^^^^ */}
      ))}
    </ul>
  </article>
);

Keys only have to be unique between siblings (eg, elements in the array you're mapping), they don't have to be globally unique ( documentation link ).键只需要在兄弟姐妹之间是唯一的(例如,您正在映射的数组中的元素),它们不必是全局唯一的( 文档链接)。

hmmm someone suggested to use tag.id, I don't think that's a thing in your code.嗯,有人建议使用 tag.id,我认为您的代码中没有这个问题。 I think they meant arr.id, but to do that I think you'd need to do something along the lines of:我认为他们的意思是 arr.id,但要做到这一点,我认为你需要按照以下方式做一些事情:

  {item.map((items, index) => (
    <Tag key={items.id} tag={items.tag} />
  ))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM