为什么要在标记单击事件上重新渲染地图?

时间:2019-05-16 06:22:43

标签: javascript reactjs google-maps react-google-maps recompose

我在集群中有带有多个标记的google map。单击标记后,我将显示信息窗口,但是当我单击标记时,将重新渲染整个地图标记和群集,这会使页面变慢且令人讨厌。

以下是我的代码:

import React, { Component } from "react";
import axios from "axios";
import { compose, withProps, withHandlers, withStateHandlers } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow
} from "react-google-maps";
const {
  MarkerClusterer
} = require("react-google-maps/lib/components/addons/MarkerClusterer");

const MapWithAMarkerClusterer = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=API&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `90vh` }} />,
    mapElement: <div style={{ height: `100%` }} />
  }),
  withStateHandlers(
    { InfoWindowobject: null },
    {
      setInfoWindow: () => value => ({ InfoWindowobject: value })
    }
  ),
  withStateHandlers(
    { isOpen: false },
    {
      onToggleOpen: ({ isOpen }) => () => ({
        isOpen: !isOpen
      })
    }
  ),
  withHandlers({
    onMarkerClustererClick: () => markerClusterer => {
      const clickedMarkers = markerClusterer.getMarkers();
    },
    onMarkerClick: props => markerss => {
      const { setInfoWindow, onToggleOpen } = props;

      axios({
        url: "API",
        method: "POST",

      }).then(res => {

        setInfoWindow(res.data);
        onToggleOpen();
      });
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap
    defaultZoom={5}
    defaultCenter={{ lat: 22.845625996700075, lng: 78.9629 }}
  >
    <MarkerClusterer
      onClick={props.onMarkerClustererClick}
      minimumClusterSize={10}
      averageCenter
      styles={[
        {
          textColor: "white",
          url: imgmapcluster,
          height: 68,
          lineHeight: 3,
          width: 70
        }
      ]}
      enableRetinaIcons
      gridSize={60}
    >
      {props.markers.map((marker, index) => (
        <Marker
          key={index}
          icon={user}
          onClick={props.onMarkerClick.bind(props, marker)}
          position={{ lat: marker.latitude, lng: marker.longitude }}
        />
      ))}
      {props.isOpen && props.InfoWindowobject !== null && (
        <InfoWindow
          position={{
            lat: props.InfoWindowobject.latitude,
            lng: props.InfoWindowobject.longitude
          }}
          onCloseClick={props.onToggleOpen}
        >
          {props.InfoWindowobject !== null && (
            <div className="infobox clearfix" style={{ fontFamily: "Gotham" }}>
              <div className="header clearfix">
                <h3>
                  {props.InfoWindowobject.name},{" "}
                  <small>{props.InfoWindowobject.contactNo}</small>
                </h3>
              </div>

            </div>
          )}
        </InfoWindow>
      )}
    </MarkerClusterer>
  </GoogleMap>
));

class DemoApp extends React.PureComponent {
  componentWillMount() {
    this.setState({ markers: [], isOpen: false, InfoWindowobject: {} });
  }

  componentDidMount() {
    axios({
      url: "API",

    }).then(res => {
      this.setState({ markers: res.data.data.list });
    });
  }

  render() {
    return (
      <MapWithAMarkerClusterer
        markers={this.state.markers}
        isOpen={this.state.isOpen}
        InfoWindowobject={this.state.InfoWindowobject}
      />
    );
  }
}

参考: https://tomchentw.github.io/react-google-maps/#markerclusterer

2 个答案:

答案 0 :(得分:1)

这是预期的行为,因为每次状态更改都会发生重新渲染。 要 prevent 重新渲染,您可以考虑将MarkerClusterer组件与shouldUpdate higher-order component包装在一起,以使React知道组件是否应受更改状态的影响,如下所示:

const MyMarkerClusterer = shouldUpdate(checkPropsChange)(props => {
  const {onMarkerClick,markers,...clusterProps}  = props;
  return (
    <MarkerClusterer 
    {...clusterProps}      
    >
      {markers.map(marker => (
        <Marker
          key={marker.photo_id}
          position={{ lat: marker.latitude, lng: marker.longitude }}
          onClick={onMarkerClick.bind(this, marker)}
        />
      ))}
    </MarkerClusterer>
  );
});

其中

const checkPropsChange = (props, nextProps) => {
  return nextProps.markers.length !== props.markers.length; //re-render only if markers prop changed 
};

Here is a demo

答案 1 :(得分:0)

import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'callback', pure: false }) export class CallbackPipe implements PipeTransform { transform(items: any[], callback: (item: any) => boolean): any { if (!items || !callback) { return items; } return items.filter(item => callback(item)); } } 调用API,并(在获取后)调用两个处理程序:onMarkerClick,'onToggleOpen`。

两个处理程序都调用状态更改的结果,并强制重新呈现嵌入的组件(setInfoWindow())。

您应将<GoogleMap/>嵌入处理程序,并将此增强组件作为子组件传递给<MarkerClusterer/>组件(或在内部进行渲染)。