why key error在React中的递归组件



我试图递归组件,但反应关键道具在根是重复的当使用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}`}
/>
))}

输入图片描述

看起来您正在为键道具使用相同的值,这就是为什么您在控制台中获得键重复错误。理想情况下,您应该为每个组件使用一个唯一的键,该键可以是您从每个组获得的唯一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://reactjs.org/docs/lists-and-keys.html #键

最新更新