每次点击标记时,我的谷歌地图都会刷新

Pet*_*ter 5 refresh reactjs react-google-maps

所以当我点击一个标记时,地图总是刷新,我该如何阻止它?单击标记将呈现有关该标记的特定信息,但它总是重新加载并返回其默认中心。

import React, { Component } from "react";
import { withGoogleMap, GoogleMap, Marker } from "react-google-maps";
import maplayout from "./mapstyle.js";


class Map extends Component {
  state = { users: []};

  onClick = (data) => {
    this.props.onClick(data);
  };

  render() {
  const GoogleMapExample = withGoogleMap(props => (
      <GoogleMap
        defaultCenter={{ lat: 47.507589, lng: 19.066128 }}
        defaultZoom={13}
      >
        {this.props.users.map((element, index) => (
          <Marker
            key = {index}
            icon={require("../assets/seenpinkek.svg")}
            position={{ lat: element.latitude, lng: element.longitude }}
            onClick={() => this.onClick(index)}
          />
        ))}
      </GoogleMap>
    ));
    return (
      <div>
        <GoogleMapExample
          containerElement={<div className="mapCont" />}
          mapElement={<div className="map" />}
          disableDefaultUI={true}
          isMarkerShown
          onClick={this.onClick}>
        </GoogleMapExample>
        </div>
    );
  }
}

export default Map;
Run Code Online (Sandbox Code Playgroud)

Vad*_*hev 1

这是预期的行为,因为父组件状态正在更新。为了防止你的地图组件重新渲染,你可以让 React 知道(通过shouldComponentUpdate方法)组件是否应该受到状态或 props 变化的影响:

shouldComponentUpdate(nextProps) {
  // If shouldComponentUpdate returns false, 
  // then render() will be completely skipped until the next state change.
  // In addition, componentWillUpdate and componentDidUpdate will not be called. 
  return false;
}
Run Code Online (Sandbox Code Playgroud)

或(允许在数据实际更改时进行更新):

shouldComponentUpdate(nextProps,nextState) {
    return (this.state.users !== nextState.users);
}
Run Code Online (Sandbox Code Playgroud)

演示

此处报告了类似问题的解决方案