[英]Refresh page with google map api in react component get error: TypeError: Cannot read property 'maps' of undefined
I googled the problems for a while, but still have no idea about how to fix it, the problem is first load is work fine, but when I refresh the page, sometimes it's not work and have error message, below is my code, hope can get me some idea, thanks!! 我用谷歌搜索了一段时间,但是仍然不知道如何解决它,问题是第一次加载可以正常工作,但是当我刷新页面时,有时它不起作用并且有错误消息,下面是我的代码,希望可以给我一些想法,谢谢!
import React, { Component } from 'react';
import './index.css'
const google = window.google;
class App extends Component {
componentDidMount() {
this.initMap();
}
initMap() {
const latLong = {lat: -25.363, lng: 131.044};
const options = {
zoom: 5,
center: latLong
};
const map = new google.maps.Map(this.refs.map, options)
const marker = new google.maps.Marker({
position: latLong,
map,
});
}
render() {
const style = {
marginLeft: "200px",
height: "400px",
width: "100%",
}
return (
<div id="app">
<div id="map" style={style} ref="map"/>
</div>
);
}
}
export default App;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>Google Map</title>
<script>function initMap() {}</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
尝试将5秒计时器设为setTimeout({},5000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.