简体   繁体   English

React中嵌套组件中的全局变量

[英]Global variables in nested components in React

I have nested component. 我有嵌套的组件。 Component Map for getting Google Map, and component for contain markers in this map. 为获得谷歌地图,以及色差分量地图为包含在这个地图标记。 Marker inside Map 地图内的标记

window.google variable available in Map component, but it undefined inside Marker comopnent. window.google变量在地图组件中可用,但在Marker组件中未定义。

Map: 地图:

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 }

So .... Why global variable window.google is good inside Map component and undefined in Marker ? 那么....为什么全局变量window.googleMap组件中很好并且在Marker中未定义?

Thanks! 谢谢!

You are checking some wrong place as I have used same to same your code in Plunker, I can access both the place window.google variable, please check below mentioned plunk for your reference. 您正在检查一些错误的地方,因为我已经使用到相同同一代码在Plunker,我可以同时访问的地方window.google变量,请检查以下内容中提到普拉克供大家参考。

Check Here 在这里检查

在此处输入图片说明

It's because method getGoogleMaps() is async and you call it in componentDidMount. 这是因为方法getGoogleMaps()是异步的,并且您在componentDidMount中调用它。 You renders Marker before Google Maps script has been loaded. 您在加载Google Maps脚本之前渲染Marker。

For example you can use isLoading state. 例如,您可以使用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>
    )
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM