[英]How do I correctly use the map method for my Array in React
I am trying to use the map method to display the parts name and exercise instead of hardcoding it, I can use the map method but I can't use it passing it with props 我正在尝试使用map方法来显示零件名称和练习,而不是对其进行硬编码,我可以使用map方法,但不能将其与道具一起传递
{course.parts.map(note => (
<p key={note.id}>
{" "}
{note.name} {note.exercises}
</p>
))}
I added this into my return body which works how can I destructure this? 我将此添加到我的返回正文中,该作品如何进行分解?
const App = () => {
const course = {
name: "Half Stack application development",
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
}
]
};
const rows = () =>
course.parts.map(note => <Course key={note.id} course={note} />);
return (
<div>
<Header course={course.name} />
{rows()}
</div>
);
};
const Course = course => {
console.log(course);
return (
<p>
{" "}
{course.name} {course.exercises}
</p>
);
};
Expected: Fundamentals of React 10 Using props to pass data 7 State of component 14 But the result is blank. 预期:React的基础知识10使用道具传递数据7组件14的状态但是结果为空。
Here you are passing course
props to your component like, 在这里,您正在将
course
道具传递给您的组件,例如,
<Course key={note.id} course={note} />
You need to access the course
props in your child component using props.course
您需要使用
props.course
在子组件中访问course
道具
const Course = (props) => {
console.log(props.course);
return (
<p>
{" "}
{props.course.name} {props.course.exercises}
</p>
);
};
or you can directly destructure your props like, 或者您可以直接破坏道具,例如
const Course = ({course}) => { //direct destructuring
console.log(course);
return (
<p>
{" "}
{course.name} {course.exercises}
</p>
);
};
You don't need this much of components to achieve your requirement. 您不需要太多的组件即可满足您的需求。 You can simply do
你可以做
const course = {
name: 'Half Stack application development',
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,
},
],
};
const App = () => {
const { name, parts } = course;
return (
<div>
<Header course={name} />
{parts.map(note => (
<p key={note.id}>{`${note.name} ${note.exercises}`}</p>
))}
</div>
);
};
Note: 注意:
I have removed the space before the paragraph but if you need it then you can change that line to 我已经删除了该段之前的空格,但是如果需要,可以将该行更改为
{ ${note.name} ${note.exercises}
} {
${note.name} ${note.exercises}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.