如何在不重新渲染Mapview的情况下更新标记位置?反应本地地图

时间:2018-08-30 23:00:12

标签: reactjs react-native react-native-maps

我正在基于标记数组状态更新多个标记位置。因此,当我使用setState更新它时,渲染功能照常触发并重新渲染mapview。由于它具有initialregion和region属性,因此它会根据玩家位置状态(我不想要这个,我只想在初始加载时使用。)

如何在不重新渲染mapview的情况下更新标记位置?

 render() {


    return (
   <MapView
   initialRegion={this.state.playerLocation}
   region={this.state.playerLocation}
      style={ styles.map }


      >
       {this.renderMarkers()}

      </MapView>




    );
  }


renderMarkers =()=>{

return(
  this.state.markers.map(marker=>{
    return(
    <Marker
      coordinate = {{
        latitude: marker.lat,
        longitude: marker.long
    }}      
    title={marker.id}
        />

    )



        })




)








}

2 个答案:

答案 0 :(得分:2)

这是React中一个非常普遍的问题,有一个很好的解决方案。

使用称为shouldComponentUpdate的生命周期方法

  

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

您可以尝试将渲染标记提取到单独的组件,然后添加lifeCycle以始终返回False。一旦安装了组件,它将不再重新渲染。

我不确定这是否会导致您的情况出现任何退步,但如果确实如此,您可以传递一个道具,该道具可以触发SCU中的重新渲染并在需要时更新标记。那是你需要玩的东西。

答案 1 :(得分:-1)

我使用了Umair Ahmed的建议,它对我完全有用。只需在shouldComponentUpdate中创建条件即可更新您的MapView并使用其他组件呈现标记。

我有:

<MapView
    key="mapView"
    onMapReady={this._onMapReady}
    region={region}
    loadingEnabled
    showsUserLocation
    showsMyLocationButton
    followsUserLocation
    ref={el => this.mapView = el}
    >
    <Markers />
</MapView>

标记是一个组件,可在地图中呈现标记,并随着标记的更改而更新。向包含的Map组件添加shouldComponentUpdate条件,以确保更新标记时不会再次完全加载Map。