我正在尝试遍历一个数组,从一个对象中提取一条信息。得到它了!但是,在获取第一个数据以从嵌套的对象数组中提取更多数据之后,我需要在同一个对象中循环遍历一个数组。任何线索我怎么能做这个工作?我尝试了多种方法。我现在坚持尝试在这个渲染函数中运行两个if语句,其中react / redux不是“喜欢”。即它不会执行第二个if语句。任何帮助表示赞赏。底部有一个我的数据结构示例谢谢!
render(){
let takePoll;
let choices;
if(this.props.polls.length > 0){
takePoll = this.props.polls.map( poll => {
if (this.props.pollId === poll.id){
return (
<div>
<h2 className="take-poll">{poll.text}</h2>
</div>
)
}
})
}
if(this.props.polls.length > 0){
let choices = this.props.polls.map(poll => {
if (this.props.pollId === poll.id){
return poll.choices.map(obj => {
return (
<div>
<h3>{obj.choice}</h3>
</div>
)
})
}
})
}
return (
<div>
{takePoll}
{choices}
</div>
)
}
//DATA STRUCTURE BELOW:
{
"id": "596dfbbc02c10a41e05a82d5",
"text": "which summer was hotter?",
"choices": [
{
"choice": "2017",
"vote": "0"
},
{
"choice": "2004",
"vote": "0"
}
],
"date": "2017-07-18T12:14:52.791Z" }
答案 0 :(得分:0)
具有相同确切变量/值检查的两个if()语句不应该是您的修复。鉴于@Anamul的建议,你可能想尝试这样的事情:
render() {
let takePoll;
let choices;
if (this.props.polls.length > 0) {
takePoll = this.props.polls.map(poll => {
if (this.props.pollId === poll.id) {
return (
<div>
<h2 className="take-poll">{poll.text}</h2>
</div>
)
}
})
choices = this.props.polls.map(poll => {
if (this.props.pollId === poll.id) {
return poll.choices.map(obj => {
return (
<div>
<h3>{obj.choice}</h3>
</div>
)
})
}
})
}
return (
<div>
{takePoll}
{choices}
</div>
)
}
答案 1 :(得分:0)
如果我是你,我会在一个循环中完成它
render(){
let takePoll = [];
let choices = [];
for(let i = 0; i < this.props.polls.length; i++) {
let poll = this.props.polls[i]
if (this.props.pollId === poll.id){
takePool.push(
<div>
<h2 className="take-poll">{poll.text}</h2>
</div>
)
choices.concat(poll.choices.map(obj => {
return (
<div>
<h3>{obj.choice}</h3>
</div>
)
}))
}
})
return (
<div>
{takePoll}
{choices}
</div>
)}
请注意我已经测试了代码