为什么在React中关键错误递归组件
我正在尝试递归组件,但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}`}
/>
))}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您正在使用相同的值为密钥支柱,这就是为什么您在控制台中获得键重复错误的原因。理想情况下,您应该为每个组件使用一个唯一的密钥,并且该密钥可能是您从每个组获得的唯一ID。类似的事情:
另外,如果您在每个组内没有任何独特的价值,则可以将 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:
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:
Docs: https://reactjs.org/docs/lists-and-keys.html#keys