簡體   English   中英

如何使用for循環在React中在地圖上渲染標記?

[英]How can I render markers on a map in React using a for loop?

我正在嘗試使用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 } />
   }
 }
  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>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM