window.google is undefined in react?

我的梦境 提交于 2021-02-04 19:51:33

问题


When I call window and console log it I get a google prop as you see here:

Yet when I try to call window.google I get undefined. Am I missing something here?


回答1:


Hey I came across a similar issue trying to instantiate a new window.google.maps.Map and found this solution helped me.

  1. When declaring your <script> tag, give it an identifier so that you can grab it later in your component.

  2. On the mounting of your component, set up a load event listener on the Google script and wait until it's ready before executing any more code.

  3. One caveat is that if your script is loaded before this component mounts (what we'd hope for in the first place) and sets up the event listener, nothing will happen. We want to catch this positive condition with if (window.google)

componentDidMount() {
  const googleScript = document.getElementById('google-map-script')

  if (window.google) {
    // All is good! Carry on 
  }

  googleScript.addEventListener('load', () => {
    // Patiently waiting to do the thing 
  })
}



回答2:


Since that looks like the Google Maps API, its probably a load order issue.

Make sure that the <script> that is pulling in the Google Maps tag comes before the one that runs your React code.

If that isn't the problem, you may need to wrap your React code in some kind of ready() function to force it to wait until the Google code is ready.




回答3:


Late answer on this, but you can simply add this const to the top of your React component, below import statements:

const google = window.google = window.google ? window.google : {}

It a) creates a variable and then b) uses the ternary operator to determine whether window.google has loaded, and c) if not, it assigns google as an empty object. H/t to @blackmamba. See this other SO question for more context.



来源:https://stackoverflow.com/questions/50030311/window-google-is-undefined-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!