首页 > 解决方案 > 如何重新渲染谷歌地图以对状态变化做出反应?

问题描述

我正在尝试按照本指南将 JavaScript Maps API 与 React.js 集成:

http://cuneyt.aliustaoglu.biz/en/using-google-maps-in-react-without-custom-libraries/

我可以让地图加载正常,一切都很好。我遇到的问题是,当状态发生变化时,我无法重新渲染地图。

本质上,我使用的是以下代码: https ://stackblitz.com/edit/react-67pggp?file=index.js

除了,我正在尝试通过状态更改来动态更改标记的位置。因此,在传递给 Map 组件的 onMapLoad() 函数中,我替换了该行

position: { lat: 41.0082, lng: 28.9784 }

与类似的东西

position: { lat: this.state.lat, lng: this.state.lng }

并且我希望标记的位置在状态中存储的位置发生变化时发生变化。我知道问题源于仅在组件首次安装时才调用 onMapLoad() 的事实,但我不确定如何让地图重新渲染并显示更新的标记位置。任何帮助表示赞赏。谢谢。

标签: javascriptreactjsgoogle-maps

解决方案


您可以使用 getInitialState 方法初始化默认状态并在渲染中使用此变量。

import React, { Component } from 'react';
import { render } from 'react-dom';
import Map from './map'

class App extends Component {
  constructor() {
    super();
  }
   getInitialState() {
    return {
       lat = '41.0082',
       lng = '28.9784'
     };
  }

  render() {
    return (
      <Map
        id="myMap"
        options={{
          center: { lat : this.state.lat ,lng : this.state.lng },
          zoom: 8
        }}
        onMapLoad={map => {
          var marker = new window.google.maps.Marker({
            position: { lat :this.state.lat, lng: this.state.lng },
            map: map,
            title: 'Hello Istanbul!'
          });
        }}
      />
    );
  }
}

render(<App />, document.getElementById('root'));

推荐阅读