javascript - React 嵌套组件中的全局变量
问题描述
我有嵌套组件。用于获取 Google Map 的组件Map ,以及用于在此地图中包含标记的组件。地图内的标记
window.google 变量在Map组件中可用,但在Marker组件中未定义。
地图:
import React from 'react'
import { Marker } from './Marker'
class Map extends React.Component {
getGoogleMaps() {
const script = document.createElement("script");
const API = 'AIzaS';
script.src = `https://maps.googleapis.com/maps/api/js?key=${API}&v=3&callback=initMap`;
script.async = true;
script.defer = true;
document.body.appendChild(script);
}
componentDidMount() {
this.getGoogleMaps()
window.initMap = () => {
var map = new window.google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {lat: 40.6947591, lng: -73.9950086},
mapTypeControl: false
})
window.map = this.map
console.log('<Map/> google:',window.google);
}
}
render() {
return (
<div>
<div id="map" ></div>
<Marker/>
</div>
)
}
}
export { Map }
:
import React from 'react'
class Marker extends React.Component {
render() {
return(
<div>
{console.log('<Marker/> google:',window.google)}
</div>
)
}
}
export { Marker }
所以....为什么全局变量window.google在Map组件中很好,而在Marker中未定义?
谢谢!
解决方案
这是因为方法getGoogleMaps()
是异步的,你在 componentDidMount 中调用它。您在加载 Google Maps 脚本之前渲染 Marker。
例如,您可以使用 isLoading 状态。
class ... {
state = {
isLoading: true
};
componentDidMount() {
this.getGoogleMaps()
window.initMap = () => {
...
window.map = this.map;
//update state here
console.log('<Map/> google:',window.google);
}
}
render() {
return this.state.isLoading
? <div>loading...</div>
: (
<div>
<div id="map" ></div>
<Marker/>
</div>
)
}
}
推荐阅读
- android - 如何为 Line-us 这样的素描机器人制作安卓应用程序?
- powershell - 使用 Add 函数的 Powershell 系统阵列
- python - 使用 numpy 数组对函数进行矢量化
- azure - 在 ubuntu 虚拟机上安装 Azure 客户端 公钥不可用
- truffle - 如何使用 Truffle 在 ThunderCore 上部署合约?
- rxjs - Observables 中是否有调用错误而不是 next 的运算符
- awk - 转换包含以下内容的(sed 或 awk 或任何东西)文件:
- javascript - 在渲染 JS 画布之前加载图像
- microsoft-graph-api - 如何追溯退回的邮件
- datastax - 使用属性键加载 DataStax 图形加载器边缘的问题