【问题标题】:My google map refreshes every time when I click on a marker每次单击标记时,我的谷歌地图都会刷新
【发布时间】:2019-01-28 18:02:21
【问题描述】:

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

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;

【问题讨论】:

  • 你能告诉我们你的this.props.onClick(data);函数吗?我认为这是因为您在某处有一个 setState 。当您调用 setState 函数时,组件正在重新渲染,这可能是您刷新的原因
  • 是的,它在我的父类中:onChild2ButtonClick = (dataFromChild2) =&gt; { this.setState({ infoIndex: dataFromChild2 }); };

标签: reactjs refresh react-google-maps


【解决方案1】:

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

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;
}

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

shouldComponentUpdate(nextProps,nextState) {
    return (this.state.users !== nextState.users);
}

Demo

已经报告了类似问题的解决方案here

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2013-08-28
    • 2015-05-09
    • 2014-07-19
    • 1970-01-01
    • 2020-09-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多