2017-05-05 93 views
0

我有一個地圖反應組件,我動態地添加標記。問題是,當我在商店中添加標記時,整個地圖重新渲染,而不是隻追加標記到地圖。有沒有人有任何建議如何可以修復?我非常肯定,我需要專門將商店注入到CPMap功能中,我只是不確定如何。MobX反應:如何只重新渲染的一部分

const CPMap = withGoogleMap((props) => (
     <GoogleMap 
      ref={props.onMapLoad} 
      style={{ 
       height: 100, 
       width: 100, 
      }} 
      onCenterChanged={props.boundsChanged} 
      defaultOptions={{ styles: this.mapStyles }} 
      defaultZoom={props.zoom} 
      defaultCenter={{ lat: props.center.lat, lng: props.center.lng }}> 
      <MarkerClusterer 
       gridSize={40}> 
       { 
        props.markers.map(({ key, position }) => (
         <Marker 
          key={key} 
          position={{ lat: position.lat, lng: position.lng }} 
          icon={{ 
           url: require('../../images/marker.png') 
          }} 
         /> 
        )) 
       } 
      </MarkerClusterer> 
     </GoogleMap > 
    )) 

    return (
     <CPMap 
      style={{ 
       height: 100, 
       width: 100, 
      }} 
      onMapLoad={(gMap) => { 
       map = gMap 
       this.props.map.fetchMarkers() 
      }} 
      boundsChanged={() => { 
       this.props.map.fetchMarkers() 
      }} 
      center={this.props.map.center} 
      zoom={this.props.map.zoom} 
      markers={mobx.toJS(this.props.map.markers)} 
      containerElement={ 
       <div style={{ height: 'calc(100vh - 70px)' } 
       } /> 
      } 
      mapElement={ 
       <div style={{ height: 'calc(100vh - 70px)' }} /> 
      } /> 
    ) 
} 

回答

0

我建議你以下解決方案:不要直接將製造商直接傳遞給CMap組件,而是使用商店來代替;

const markersStore = observable({ 
    markers: [] 
}); 

然後在你的組件 - 移動MarkersClusterer到單獨的組件,並通過markersStore更深一層:

//import markersStore or inject via mobx-react package 
class MyComponent extends Component { 
    render() { 
     const CMap = withGoogleMap((props) => (
     <GoogleMap 
      ... 
      <Clusterer markersStore={props.markersStore} /> 
     /> 
    )) 
     return (
     <CMap 
      ... 
      markersStore={markersStore} 
     /> 
    ) 
    } 
} 

讓您的新的羣集組件可觀察到的,因此更新時markersStore「標誌」屬性更新;

@observable 
class Clusterer extends Component { 
    render(){ 
     const { markers } = this.props.markersStore; 
     return (
      <MarkerClusterer> 
       { markers.map(...)} 
      </MarkerClusterer> 
     ) 
    } 
} 

最後的變化是如此之填充markersStore用新數據更新您的fetchMarkers方法。

使用此解決方案CMap組件不知道標記的任何內容,並且在收到新數據時不會更新。與此同時,MarkersClusterer組件變得更加聰明,並且「觀察」markersStore中的更改。