我之前使用map((循环遍历对象中单个道具的值。
const Content = (p)=>{
console.log(p)
const {parts} =p
return (
<div>
{parts.map((item)=>
<Part key={item.id} part={item.name} exercise={item.exercises}/>
)}
</div>
)
}
现在对象被扩展为一个对象数组,我将如何循环遍历我的值?
const course = [
{
name:'Half Stack application development',
id:1,
parts: [
{
name:'Fundamentals of React',
exercises: 10,
id: 1
},
{
name:'Using props to pass data',
exercises:7,
id: 2
},
{
name:'State of a component',
exercises:14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
我应该在地图中使用地图吗?如果是,我应该如何实现它?
有很多方法,其中一种是:
只需在返回语句之前创建一个JSX元素数组。直接渲染该阵列。这是一个带有p
标签的简单exmaple。您可以使用自己的组件:
import "./styles.css";
export default function App() {
const course = [
{
name:'Half Stack application development',
id:1,
parts: [
{
name:'Fundamentals of React',
exercises: 10,
id: 1
},
{
name:'Using props to pass data',
exercises:7,
id: 2
},
{
name:'State of a component',
exercises:14,
id: 3
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
];
let comp = [];
course.forEach((p) => {
comp = [comp, ...(p.parts).map((item)=>
<p key={item.id}>{item.name}</p>
)];
});
return (
<div>
{comp}
</div>
)
}
沙盒
您可以嵌套循环。
{course.map((item)=>
{
items.parts.map((p)=><Part key={p.id} part={p.name} exercise=
{p.exercises}/> )
}
)}
一个简单的方法是将flatMap与map:结合使用
<div>
{
course.flatMap(el1 => el1.parts.map(el2 =>
<Part key={el2.id} part={el2.name} exercise={el2.exercises} />
)
}
</div>