首页 > 解决方案 > 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中未定义?

谢谢!

标签: javascriptreactjsgoogle-maps

解决方案


这是因为方法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>
    )
  }
}

推荐阅读