我目前正在使用react-static和集成来自CMS的数据。我确信这是一个非常基本的东西,但是我大脑已经被炒了,看不到我错过的东西。简而言之,我从CMS的菜单中提取导航项的JSON。各个导航项目包含在菜单对象的项目键中。我试图遍历它们并构建我的导航组件。
如果我只是将变量设置为items对象,则构建正常。然而,因为它是一个物体,我似乎无法正确地挖掘它。
这是我的功能
renderMenu() {
return menus.items.map((menu) => {
return (
<NavItem>
<Link to={menu.object_slug} className="nav-link">{menu.title}</Link>
</NavItem>
)
})
}
以下是JSON的一小部分示例
{
"ID" : 2,
"name" : Primary Navigation,
"slug" : primary-navigation,
"description" : ,
"count" : 9,
"items" : -[
-{
"id" : 11,
"order" : 1,
"parent" : 0,
"title" : About,
"url" : http:\/\/www.attorneytemplate.dev.php72-38.lan3- 1.websitetestlink.com\/about\/,
"attr" : ,
"target" : ,
"classes" : ,
"xfn" : ,
"description" : ,
"object_id" : 2,
"object" : page,
"object_slug" : about,
"type" : post_type,
"type_label" : Page
},
{
"id" : 21,
"order" : 2,
"parent" : 0,
"title" : Practice Areas,
"url" : #,
"attr" : ,
"target" : ,
"classes" : ,
"xfn" : ,
"description" : ,
"object_id" : 21,
"object" : custom,
"object_slug" : practice-areas,
"type" : custom,
"type_label" : Custom Link,
"children" : -[
-{
"id" : 26,
"order" : 3,
"parent" : 21,
"title" : Practice Area 1,
"url" : http:\/\/www.attorneytemplate.dev.php72-38.lan3-1.websitetestlink.com\/practice-area\/practice-area-1\/,
"attr" : ,
"target" : ,
"classes" : ,
"xfn" : ,
"description" : ,
"object_id" : 13,
"object" : practice-area,
"object_slug" : practice-area-1,
"type" : post_type,
"type_label" : Practice Area
},
{
"id" : 25,
"order" : 4,
"parent" : 21,
"title" : Practice Area 2,
"url" : http:\/\/www.attorneytemplate.dev.php72-38.lan3-1.websitetestlink.com\/practice-area\/practice-area-2\/,
"attr" : ,
"target" : ,
"classes" : ,
"xfn" : ,
"description" : ,
"object_id" : 15,
"object" : practice-area,
"object_slug" : practice-area-2,
"type" : post_type,
"type_label" : Practice Area
}
]
}
]
}
另外,第二个问题我如何处理儿童用品?
答案 0 :(得分:0)
您似乎没有将'menus'对象正确传递给包含renderMenu()
函数的组件。
我已经基于你的Json示例创建了一个菜单,看起来它渲染得很好:
https://codesandbox.io/s/k5plnv2vm5
要迭代子项,请添加以下代码:
return menus.items.map((menu, i) => {
return (
<div key={i}>
<a href={menu.object_slug} className="nav-link">{menu.title}</a>
{(menu.children) ? (
menu.children.map((children, i) => {
return (
<li key={'children-'+i}>
<a href={children.object_slug} className="nav-link">{children.title}</a>
</li>
)
})
): null}
</div>
)
})