我正在试验 React,我想在 map 上渲染一些标记(我正在使用 Google Maps API)。 现在,如果我对标记进行硬编码(在示例中,5 个标记,每个具有不同的坐标、名称和描述,如下面的位置数组所示),一切都很好。 但是,如果我想遍历数组并在完全不进行硬编码的情况下渲染它们怎么办?我在 render() 之前定义了 renderMarkers 函数。 任何帮助,将不胜感激。谢谢!
/* Main component state */
state = {
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
mapReady: true,
desc: '',
animation: null,
locations:
[
{
"locationName": "name1",
"position": '{"lat": "lat1", "lng": "lng1"}',
"desc": "desc1"
},
{
"locationName": "name2",
"position": '{"lat": "lat2", "lng": "lng2"}',
"desc": "desc2"
},
{
"locationName": "name3",
"position": '{"lat": "lat3", "lng": "lng3"}',
"desc": "desc3"
},
{
"locationName": "name4",
"position": '{"lat": "lat4", "lng": "lng4"}',
"desc": "desc4."
},
{
"locationName": "name5",
"position": '{"lat": "lat5, "lng": "lng5"}',
"desc": "desc5."
}
]
};
/* Function to render the markers, each with their relevant info taken from the state.locations array, on the map */
renderMarkers = () => {
for (let i = 0; i < this.state.locations.length; i++) {
return <Marker
onClick = { this.onMarkerClick }
title = { this.state.locations[i].locName }
position = { JSON.parse(this.state.locations[i].position) }
desc = { this.state.locations[i].desc }
animation = { this.state.animation[i] }
name = { this.state.locations[i].locName } />
}
}
最佳答案
- 使用
map
函数创建标记数组。 renderMarkers
函数应该放在render
函数之外。否则,每次组件状态更改时都会重新创建renderMarkers
,因为每次状态更改(性能影响)时都会调用render
。
renderMarkers() {
return this.state.locations.map((location, i) => {
return <Marker
key={ i }
onClick = { this.onMarkerClick }
title = { location.locName }
position = { JSON.parse(location.position) }
desc = { location.desc }
animation = { this.state.animation[i] }
name = { location.locName } />
})
}
render() {
return <div>{ this.renderMarkers() }</div>
}
关于javascript - 如何使用 for 循环在 React 中的 map 上渲染标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51611374/