使用 react 添加 Google 地图时出错 - 类型错误:无法读取未定义的属性'maps'



// App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Map from "./Map.js"
class App extends React.Component {
constructor(props) {
super(props);
this.loadScript = this.loadScript.bind(this);
}
loadScript() {
const API_KEY = process.env.REACT_APP_API_KEY;
const url = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&libraries=places`;
const s = document.createElement("script");
s.src = url;
document.head.appendChild(s);
}
componentWillMount() {
this.loadScript();
}
render() {
return (
<div>
<Map />
</div>
);
}
}
export default App;

//Map.js
import React from "react"
export default class Map extends React.Component {
constructor(props) {
super(props);
this.loadMap = this.loadMap.bind(this);
}
loadMap() {
const map = new window.google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
}
componentWillMount() {
this.loadMap();
}
render() {
return (
<div id="map" style={{ width: 100, height: 100 }}></div>
);
}

}

嗨,我是React的新手,我正在尝试在没有第三方库帮助的情况下加载谷歌地图。

我已经动态地创建了一个脚本标记,并将其插入到DOM中。我在尝试访问脚本中的变量时遇到了这个错误。

我的猜测是,在加载脚本之前就已经访问了"maps"。我不知道如何修复这个错误。

以编程方式加载脚本时,您可以侦听"onload"事件,并在加载脚本时执行其余逻辑。在这种情况下,loadScript函数可能如下所示:

loadScript() {
const API_KEY = process.env.REACT_APP_API_KEY;
const url = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&libraries=places`;
const s = document.createElement("script");
s.src = url;
document.head.appendChild(s);
s.onload = function(e){
console.info('googleapis was loaded');            
}
}

您可以向应用程序组件添加scriptLoaded状态,并在onload函数中更改它,在这种情况下,仅当scriptLoadedtrue:时才需要渲染

<div>
{this.state.scriptLoaded && <Map />}
</div>

最新更新