[英]Using the same index to map two arrays in React.js
I want to display a table in React. 我想在React中显示一个表格。 The first column is all the courses taught by the prof, and the second column is at most three comments associated with that course.
第一列是教授教授的所有课程,第二列是与该课程相关的最多三个注释。 Data for all the courses are stored at
所有课程的数据都存储在
this.state.courses
All the comments are nested array mapping to the course order. 所有评论都是嵌套数组映射到课程顺序。 Access comments for the first course is
访问第一门课程的评论是
this.state.comments[0]
My code for now did not work, but this is my attempt 我的代码目前无法正常工作,但这是我的尝试
<Table striped bordered hover>
<thead>
<tr>
<th>{`Courses Taught By ${this.state.professorname}`}</th>
<th>{`Comments on Course`}</th>
<th>{`Comments on Prof`}</th>
</tr>
</thead>
<tbody>
<tr>
{this.state.courses.map((course, i) => (
<td key={i}>
<Link to={`/${this.state.id}/${course._id}`}>{course.name}</Link>
</td>
))}
{this.state.comments[i].map((comment, j) => {
<td key={j}>
<p>{this.state.comments[i][j]}</p>
</td>
})}
</tr>
</tbody>
</Table>
I could really the help for this one. 我真的可以为这个提供帮助。 Thanks!
谢谢!
The second loop is out of the scope of the first one - it does not have access to i
. 第二个循环不在第一个循环的范围之内-它无法访问
i
。
You should move the second map
inside the first one, to be able to access it. 您应该将第二张
map
移到第一张map
内,以便能够访问它。
<tr>
{this.state.courses.map((course, i) => (
<>
<td key={course._id}>
<Link to={`/${this.state.id}/${course._id}`}>{course.name}</Link>
</td>
{this.state.comments[i].map((comment, j) => (
<td key={j}>
<p>{this.state.comments[i][j]}</p>
</td>
))}
</>
))}
</tr>
Two problem I can see in your code. 我可以在您的代码中看到两个问题。
First i
from first loop is not available in second loop(out of scope). 第一个循环中的第一个
i
在第二个循环中不可用(超出范围)。
Second you are not returning anything in second map functions. 其次,您在第二个地图函数中未返回任何内容。
<tr>
{this.state.courses.map((course, i) => (
<>
<td key={course._id}>
<Link to={`/${this.state.id}/${course._id}`}>{course.name}</Link>
</td>
{this.state.comments[i].map((comment, j) => {
return (
<td key={j}>
<p>{this.state.comments[i][j]}</p>
</td>
)
})}
</>
))}
</tr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.