【发布时间】:2021-11-29 19:20:49
【问题描述】:
我将索引作为唯一键传递,但我仍然收到此警告:
警告:列表中的每个孩子都应该有一个唯一的“key”属性。
查看SectionPackages的渲染方法
谁能指导我可能是什么问题?
const SectionPackages = props => {
const listingPackages =
publicData && publicData.packages && publicData.packages.length
? [defaultPackage, ...publicData.packages]
: [];
useEffect(() => {
listingPackages.map((l, index) => {
hidden[index] = true;
setHidden([...hidden]);
});
}, []);
return (
<div className={listingPackages.length ? rootClassName : css.noPackages}>
{listingPackages.length > 0 && (
<h2 className={css.packagesMainTitle}>
<FormattedMessage id="SectionPackages.title" />
</h2>
)}
{listingPackages.map((listingPackage, index) => {
const moneyPrice = new Money(
listingPackage.price.amount * 100,
listingPackage.price.currency
);
return (
<a onClick={e => handleBtnClick(e, index)} key={index}>
<div
key={index}
className={
selectedPackage === index && selectedPackage !== null
? classNames(css.packagesContainer, css.packagesSelectedContainer)
: css.packagesContainer
}
>
<div className={css.packagesDescriptionHolder}>
{listingPackage.description != null && (
<p
className={
hidden[index] === true
? classNames(css.packagesDescriptionHidden, 'packagesDescription')
: classNames(css.packagesDescriptionShown, 'packagesDescription')
}
>
{listingPackage.description}
</p>
)}
{elHeight[index] && elHeight[index].index === index && elHeight[index].height > 40 && (
<p
className={css.packagesDescriptionMore}
onClick={e => showHideDescription(e, index)}
>
{hidden[index] === true ? (
<FormattedMessage id="SectionPackages.showMore" />
) : (
<FormattedMessage id="SectionPackages.showLess" />
)}
</p>
)}
</div>
</div>
</a>
);
})}
</div>
);
};
【问题讨论】:
-
我没有看到此代码有任何直接问题,React 键使用的是映射数组索引,因此它不能重复。你是否在这个 React 组件子树中的任何其他地方映射了任何东西?您能否将完整的错误消息和堆栈跟踪(如果有)添加到您的问题中?
-
@DrewReese 已添加,请查看
-
谢谢,仍然不清楚在哪里可能出现重复键。认为您可以为该组件创建一个 running 代码和框,其中包含模拟数据/道具,以重现我们可以实时检查和调试的关键问题?
标签: reactjs