简体   繁体   English

如何在react js中映射包含对象的嵌套数组?

[英]How to map nested array containing objects in react js?

Im not really sure if the question is right but here is the problem:我不确定这个问题是否正确,但问题是:

 const course = [
{
  name: 'Half Stack application development',
  id: 1,
  parts: [
    {
      name: 'Fundamentals of React',
      exercises: 10,
      id: 1
    },
    {
      name: 'State of a component',
      exercises: 14,
      id: 3
    },
    {
      name: 'Redux',
      exercises: 11,
      id: 4
    }
  ]
}, 
{
  name: 'Node.js',
  id: 2,
  parts: [
    {
      name: 'Routing',
      exercises: 3,
      id: 1
    },
    {
      name: 'Middlewares',
      exercises: 7,
      id: 2
    }
  ]
}

] ]

The exercise here is to render this array, but it has to be in a way that more courses can be added later and from components.这里的练习是渲染这个数组,但它必须以一种可以在以后从组件添加更多课程的方式。 Here are my components that im trying to make:这是我尝试制作的组件:

     const Content = (props) => {
 return(
  props.parts.map(part => {
    console.log(part.parts,'part', part.id)
  })
  )
}



const Part = (props) =>{
 console.log(props)
  return <div>
    {props.part.name}
  </div>}

I have the data i want in the map, but I just dont get how to make the indexes dynamic... Like in the map it would go through all of the arrays sub-parts and give the names and exercises我在地图中有我想要的数据,但我只是不知道如何使索引动态...就像在地图中一样,它会遍历所有数组子部分并给出名称和练习

Like I mentioned in the comments, it sounds like what you are missing is the dynamic rendering of components based on an array of data.就像我在评论中提到的那样,听起来您缺少的是基于数据数组的组件动态渲染。 The primary issue is you need to update the Content component to actually render a Part for every item in the parts array.主要问题是您需要更新Content组件以实际为部件数组中的每个项目渲染一个Part That would look something like this那看起来像这样

const Content = ({parts}) => {
  return (
    <>
      { parts.map(part => <Part key={part.id} part={part) />) }
    </>
  )
}

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

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