javascript - 如何重新渲染谷歌地图以对状态变化做出反应?
问题描述
我正在尝试按照本指南将 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() 的事实,但我不确定如何让地图重新渲染并显示更新的标记位置。任何帮助表示赞赏。谢谢。
解决方案
您可以使用 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'));
推荐阅读
- spring-boot - Redis 异常:无法确定要读取的节点
- database - 如何将 oracle 转储文件上传到 oracle 数据库:AWS RDS
- ruby-on-rails - 如何在 Rails 5 项目中安装 Devise?
- javascript - json解析并获取成绩内的对象
- php - 中间件身份验证将 api 路由重定向到 /home
- java - 想要将 org.bytedeco.javacpp.lept.PIX 转换为 byte[] 和 Buffered Image
- php - 如何在 Drupal8 中向“站点信息”表单添加新的自定义字段
- mysql - 将 CSV 文件加载到表时日期值不正确
- jquery - 在 Rails 中将 $.ajax 更改为 $post
- php - SugarCRM Rest api 函数响应总是被最后 2 个字符修剪