React - 如何映射嵌套对象值? [英] React - how to map nested object values?
问题描述
我只是想在状态对象中映射嵌套值。数据结构如下所示:
I am just trying to map nested values inside of a state object. The data structure looks like so:
I想要映射每个里程碑名称,然后映射该里程碑内的所有任务。现在我正在尝试使用嵌套的地图函数,但我不确定我是否可以这样做。
I want to map each milestone name and then all tasks inside of that milestone. Right now I am trying to do so with nested map functions but I am not sure if I can do this.
渲染方法如下所示:
render() {
return(
<div>
{Object.keys(this.state.dataGoal).map( key => {
return <div key={key}>>
<header className="header">
<h1>{this.state.dataGoal[key].name}</h1>
</header>
<Wave />
<main className="content">
<p>{this.state.dataGoal[key].description}</p>
{Object.keys(this.state.dataGoal[key].milestones).map( (milestone, innerIndex) => {
return <div key={milestone}>
{milestone}
<p>Index: {innerIndex}</p>
</div>
})}
</main>
</div>
})}
</div>
);
}
我认为我可以以某种方式通过传递这行代码的内部索引: {Object.keys(this.state.dataGoal [key] .milestones)
所以看起来像这样: { Object.keys(this.state.dataGoal [key] .milestones [innerIndex])
。
I think that I could somehow achieve that result by passing the inner index to this line of code: {Object.keys(this.state.dataGoal[key].milestones)
so it would look like: {Object.keys(this.state.dataGoal[key].milestones[innerIndex])
.
但我不知道如何通过 innerIndex
up。我还尝试通过 {milestone.name}
获取里程碑名称,但这也不起作用。我想这是因为我必须指定密钥。
But I am not sure how to pass the innerIndex
up. I have also tried to get the milestone name by {milestone.name}
but that doesn't work either. I guess that's because I have to specify the key.
有人有想法吗?或者我应该以完全不同的方式映射整个对象?
Does anybody have an idea? Or should I map the whole object in a totally different way?
很高兴任何帮助,
Jakub
Glad for any help, Jakub
推荐答案
您可以使用嵌套地图映射里程碑,然后映射任务数组:
You can use nested maps to map over the milestones and then the tasks array:
render() {
return (
<div>
{Object.keys(this.state.dataGoal.milestones).map((milestone) => {
return {this.state.dataGoal.milestones[milestone].tasks.map((task, idx) => {
return (
//whatever you wish to do with the task item
)
})
})}
</div>
)
}
这篇关于React - 如何映射嵌套对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!