问题
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.
When declaring your
<script>tag, give it an identifier so that you can grab it later in your component.On the mounting of your component, set up a
loadevent listener on the Google script and wait until it's ready before executing any more code.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