我有一个位置数组,试图在页面上显示其值,我使用了以下代码来遍历该数组:
{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)
我不确定自己在做什么错。任何帮助,将不胜感激。
.forEach 方法只是迭代数组元素,但不返回任何内容。
如果locations是Array使用.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)
如果locations是Set使用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 添加到映射的元素。
推荐阅读:
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |