javascript - 为什么要在标记点击事件上重新渲染 map ?

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

我有带有集群的多个标记的谷歌地图。单击标记时,我会显示信息窗口,但是当我单击标记时,整个 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

最佳答案

这是预期的行为,因为每次状态更改时都会重新渲染。 要防止 重新呈现,您可以考虑使用 shouldUpdate higher-order component 包装 MarkerClusterer 组件。让 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

关于javascript - 为什么要在标记点击事件上重新渲染 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162025/

相关文章:

javascript - 设置 map 缩放以覆盖所有标记;确保以特定标记为中心

javascript - jQuery:滚动时使行变长

javascript - 如何将多个值存储到一个可重用变量中 - ReactJs

javascript - React 无状态功能组件应返回 null 但收到错误

javascript - 在面板中添加一个 div 元素?

javascript - 如何获取谷歌地图图像采集日期?

javascript - 我想关闭通过后端C#进程打开的firefox浏览器

c# - 将值连接到隐藏变量

javascript - JSON 解析 Promise 行为不正常

javascript - 防止组件卸载 - 在打开其他组件之前向用户显示通知