简体   繁体   English

Next.js JSON 嵌套

[英]Next.js JSON Nested

I'm trying to read the data of the JSON in Next.JS and can't get past the nested array.我正在尝试读取 Next.JS 中 JSON 的数据,但无法通过嵌套数组。 I can get the first.map logic to work.我可以让 first.map 逻辑工作。 I want to print out the data in the below section of the JSON.我想打印出 JSON 下面部分的数据。

I can get Home, One and Two printed out.我可以打印出家、一和二。 Just need to print Three and Four that is in the below array.只需要打印下面数组中的三和四。 I thought using "menuItem.below.map(childItem => (" would work.我认为使用“menuItem.below.map(childItem => (”会起作用。

TypeError: Cannot read properties of undefined (reading 'map')
{menuItem.below.map(childItem => (

Here is the Json.这是 Json。

[
{
"key": "standard.front_page",
"title": "Home",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "700d2d65-0307-471a-b843-c09ffcae0d9b",
"title": "One",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "51270262-f99d-4557-ad55-8bd8727ab15f",
"title": "Two",
"absolute": "http://localhost:8888/",
"relative": "/",
"below": [
{
"key": "f23a85d8-f430-47c8-87a1-c965d4078d0c",
"title": "Three",
"absolute": "http://localhost:8888/",
"relative": "/"
},
{
"key": "89b2d6b2-81d0-4d85-a0eb-8ce4e3dac80e",
"title": "Four",
"absolute": "http://localhost:8888/",
"relative": "/"
}
]
}
]
function MainMenu({ menuLists }) {
  return (
   <div>
      {menuLists.map(menuItem => (
        <div>
          <Link href={menuItem.absolute}><a>{menuItem.title}</a></Link>

          {menuItem.below.map(childItem => (
            <div>{childItem.title}</div>
          ))}
        </div>

      ))}
  </div>
  )
}

export async function getStaticProps() {

  const response = await fetch('http://localhost:8888/api/menu_items/main', config);
  const menuLists = await response.json();
  
  return {
    props: {
      menuLists: menuLists,
    },
  }
}

export default MainMenu

The below property is not always present in the menuItems, so you must first make sure it exists: below属性并不总是出现在 menuItems 中,因此您必须首先确保它存在:

{menuItem.below && menuItem.below.map(childItem => (
   <div>{childItem.title}</div>
))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM