我正在使用 ReactJS、NextJS 14、Tailwind CSS 和 Framer Motion。
我必须在 React 中为每个重复的子项放置唯一的键,所以我必须在 NextJS 中这样做。这也是为什么我将子项的索引值作为它们的键,因为索引值是唯一的,对于数组的每个元素都会加一。然而,警告一直说我什么也没放。我无法理解,所以:我在控制台中记录了该值,它显示了预期的数字(0、1、2...);将该值更改为
linkInfo
的属性之一,这是唯一的;我什至试图把 Date.now()
放在那里。它们都向我展示了预期的唯一值,但警告是相同的:
Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behaviour is unsupported and could change in a future version.
这是导致该问题的代码。当我删除这段代码后,问题就消失了。
{menuFocusLevel === 2 && (
<motion.div
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 10 }}
transition={{ duration: 0.16, type: "spring" }}
className="absolute top-7 -right-1 bg-black w-48 border border-red flex flex-col py-0.5 rounded-l-sm rounded-br-sm"
>
{links.map((linkInfo, menuLinkIdx) => (
<MemoriesLink key={menuLinkIdx} {...linkInfo} isInMenu />
))}
</motion.div>
)}
我尝试添加重复的子项,我希望他们不会在键上犯任何错误。
问题解决了。我是 Framer Motion 的问题。我用
<AnimatePresence />
包装了该代码。但是,在该标签内部有两个 <motion.div />
标签,这导致了按键问题。在每个 <AnimatePresence />
标签中分离两个组件后,警告消失了。再见,遇见先生。很有趣,我不想再见到你了。