为什么在React中关键错误递归组件

发布于 2025-01-31 06:28:05 字数 668 浏览 2 评论 0原文

我正在尝试递归组件,但React关键道具在root中重复 使用UUID时,很好。我不知道原因,请帮助我

// filterModal.jsx
<FilterGroupCollection
            parentFiltergroup={parentFiltergroup}
            setParentFilterGroup={setParentFilterGroup}
            name='a'
/>
{parentFiltergroup.groups?.map((group, idx) => (
          <FilterGroupCollection
            key={name}
            parentFiltergroup={group}
            setParentFilterGroup={setParentFilterGroup}
            name={`${name}-${idx + 1}`}
          />
        ))}

在此处输入图像描述

i'm trying to recursion components but react key props is duplicate in root
when using uuid, is fine. i don't know reason, help me

// filterModal.jsx
<FilterGroupCollection
            parentFiltergroup={parentFiltergroup}
            setParentFilterGroup={setParentFilterGroup}
            name='a'
/>
{parentFiltergroup.groups?.map((group, idx) => (
          <FilterGroupCollection
            key={name}
            parentFiltergroup={group}
            setParentFilterGroup={setParentFilterGroup}
            name={`${name}-${idx + 1}`}
          />
        ))}

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

旧时浪漫 2025-02-07 06:28:05

看起来您正在使用相同的值为密钥支柱,这就是为什么您在控制台中获得键重复错误的原因。理想情况下,您应该为每个组件使用一个唯一的密钥,并且该密钥可能是您从每个组获得的唯一ID。类似的事情:

{parentFiltergroup.groups?.map((group, idx) => (
 <FilterGroupCollection
   key={group.id} //notice here the id that you should get from each group
   parentFiltergroup={group}
   setParentFilterGroup={setParentFilterGroup}
   name={`${name}-${idx + 1}`}
 />
))}

另外,如果您在每个组内没有任何独特的价值,则可以将 idx 用作关键,但这不是React解释的好习惯:

如果项目的顺序可能会更改,我们不建议将索引用于键。这可能会对性能产生负面影响,并可能引起组件状态的问题。

文档: https://reaectjs.s.org/docs/docs/docs/lists-and-lists-and-keys。 html#键

It looks like you are using the same value for the key prop and that's why you are getting the key duplicate error in the console. Ideally you should use a unique key for each component, and that key could be a unique id that you get from each group. Something like this:

{parentFiltergroup.groups?.map((group, idx) => (
 <FilterGroupCollection
   key={group.id} //notice here the id that you should get from each group
   parentFiltergroup={group}
   setParentFilterGroup={setParentFilterGroup}
   name={`${name}-${idx + 1}`}
 />
))}

Alternatively, if you do not have any unique value inside each group, you can use the idx as key but this is not a good practice as explained by 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.

Docs: https://reactjs.org/docs/lists-and-keys.html#keys

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