gpt4 book ai didi

javascript - React : flattenChildren(. ..): 遇到两个拥有相同 key 的 child

转载 作者:行者123 更新时间:2023-12-01 03:24:18 25 4
gpt4 key购买 nike

我知道这个问题之前已经被问过,但我不确定我是否理解这里发生的事情。我有一个对象数组,我在 React 组件中映射它们以创建导航:某些元素可能有子元素,因此我为这些元素添加第二个 .map 函数。一切正常,但第二个子元素未显示,因为它“遇到两个具有相同键的子元素”。很困惑。。有谁能解释一下为什么吗?我使用标题作为键,它现在是唯一的。

这是我的项目数组

let navItems = [
{
title: "Home",
href: "/",
children: []
},
{
title: "Evaluations",
href: "/evaluations",
children: [
{
id: 1,
title: "List all evalutions",
href: "/"
},
{
id: 2,
title: "Planner",
href: "/"
},
]
}
]

这是代码:

let items = this.props.items.map((item) => {
if(item.children.length > 0) {
return item.children.map((child) => {
return <li className="menu--item" key={ item.title }>
<a href={ item.href } className="menu--link">{ item.title }</a>
<ul className="dropdown">
<li key={ child.title }><a href="{ child.href}">{ child.title }</a></li>
</ul>
</li>
})
} else {
return <li className="menu--item" key={ item.title }>
<a href={ item.href } className="menu--link">{ item.title }</a>
</li>
}
})

最佳答案

发生这种情况是因为您正在映射 item.children但返回一个 key item.title里面。 item.title在该循环内不会改变,因此最终得到 2 <li>键为“Evaluations”的元素。我怀疑您想使用 map里面<ul className="dropdown"> .

let items = this.props.items.map((item) => {
if(item.children.length > 0) {
return <li className="menu--item" key={ item.title }>
<a href={ item.href } className="menu--link">{ item.title }</a>
<ul className="dropdown">
{item.children.map((child) => {
return <li key={ child.title }><a href="{ child.href}">{ child.title }</a></li>
})}
</ul>
</li>
} else {
return <li className="menu--item" key={ item.title }>
<a href={ item.href } className="menu--link">{ item.title }</a>
</li>
}
})

关于javascript - React : flattenChildren(. ..): 遇到两个拥有相同 key 的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44949458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com