2017-07-19 125 views
0

我想通过一个数组来循环从一个对象中拉出一块信息。得到它了!但是,我需要在获取第一块数据以从嵌套的对象数组中获取更多数据之后,循环访问同一对象中的数组。任何线索我怎么能做到这一点?我尝试了多种方式。我现在坚持试图在这个渲染函数中运行两个if语句,它反应/ redux不是“喜欢”。即它不会执行第二条if语句。任何帮助表示赞赏。在底部有一个我的数据结构示例谢谢!通过一个对象循环,然后通过一个嵌套的对象数组 - javascript react/redux

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" } 
+1

选择已经通过让选择来定义,你不能再定义它。再次移除let标签。 – error404

回答

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> 
) 
} 
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> 
)} 

注意,我已经测试的代码,但