javascript - 如何使用 for 循环在 React 中的 map 上渲染标记?

标签 javascript reactjs google-maps for-loop react-google-maps

我正在试验 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 } />
   }
 }

最佳答案

  1. 使用 map 函数创建标记数组。
  2. 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/

相关文章:

html - 如何将 SVG 图像(其路径具有负值)正确定位到 Google Map

javascript - 在 Angular 4 中使用发布请求时出现 400 错误

javascript - 从构造函数启动单个实例并将其用作另一个类中的静态方法

javascript - 当变量在单独的循环中定义时,在循环内调用该变量

reactjs - 将本地镜像路径作为两个功能组件之间的 prop 传递

reactjs - React Query 使用旧数据进行重新获取

javascript - 如何将我的 Google map 变成图像?并且不能使用鼠标移动?

javascript - 单击时将文本 append 到文本区域?

javascript - 样式组件/ react

javascript - Google Streetview API Indoor panorama.setPosition() 重定向到起始位置