我正在试验React,我想在地图上渲染一些标记(我使用的是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>
}