反应-在数组中显示项目的问题

1 foreach reactjs

我有一个位置数组,试图在页面上显示其值,我使用了以下代码来遍历该数组:

{this.props.locations && this.props.locations.forEach(loc => {
    console.log("Location: "+loc)
    return(
        <span>Location is: {loc}</span>
    )
})} 
Run Code Online (Sandbox Code Playgroud)

页面上的结果为空: 在此处输入图像描述, 但是它正确记录了位置: 在此处输入图像描述

我在App.js中获得this.props.locations的值,如下所示:

 var locations = this.state.cardLists
      var distictLocations = new Set()
      locations.forEach(location => {
        if(!distictLocations.has(location.Location))
        {
          distictLocations.add(location.Location)
        }
      });
     this.setState({
       locations: distictLocations
     })
Run Code Online (Sandbox Code Playgroud)

我不确定自己在做什么错。任何帮助,将不胜感激。

aba*_*yan 6

.forEach 方法只是迭代数组元素,但不返回任何内容。

如果locationsArray使用.map

{
    this.props.locations && this.props.locations.map(loc => {
        console.log("Location: " + loc)
        return (
            <span>Location is: {loc}</span>
        )
    })
}
Run Code Online (Sandbox Code Playgroud)

如果locationsSet使用Array.from

{
    this.props.locations && Array.from(this.props.locations, loc => {
        console.log("Location: " + loc)
        return (
            <span>Location is: {loc}</span>
        )
    })
}
Run Code Online (Sandbox Code Playgroud)

key出于性能原因,还建议将prop 添加到映射的元素。


推荐阅读:

forEach vs地图

Array.from

React中的列表和键

对帐和密钥