首页 > 解决方案 > ReactJS:带有条件表达式的嵌套 .map 以匹配值

问题描述

我有两个数组 this.state.race { "raceName": "President", "raceID": 100
}

this.state.candidates (例如) { "canName": "John", "canID": 1, "raceID": 100
}, { "canName": "David", "canID": 2, "raceID": 100
},{“canName”:“莎莉”,“canID”:3,“raceID”:101
}

我想显示所有种族,并且只显示具有匹配raceid 的候选人

所以它会是这样的:

第 100 场比赛:1. 约翰 2. 大卫 第 101 场比赛:{空列表}

我的代码是这样的:

render() {
  return (
    {this.state.racelist.map(myrace => (
       {myrace.title}
       <divider />
       {this.state.candidatelist.map(mycand => (
          {/********************************************************
          how can i put a conditional statment here that checks to see if,
          mycand.raceID === myrace.raceID  ???? and if those match, render
          mycand info
          ********************************************************/}
       ))}
    ))}
  )
}

标签: arraysreactjsloopsnested

解决方案


  1. 返回空

list.map(item => if(condition) item else null)

  1. 使用过滤器

list.filter(condition).map(renderItem)


推荐阅读