Javascript Can';t从React应用程序的卸载页面中删除Google地图自动完成库脚本
我在React应用程序中使用google maps autocomplete,但我在componentwillUnmount生命周期事件中遇到错误,即: this.autocomplete.removeListener不是函数 当我回到组件时,我得到以下错误: 您已多次在此页面上包含Google Maps API。 这可能会导致意外错误 在使用devtools检查页面元素时,似乎有多个脚本标记包含* 添加到html页面的页眉 如果我注释掉组件中的Javascript Can';t从React应用程序的卸载页面中删除Google地图自动完成库脚本,javascript,google-maps,reactjs,google-maps-api-3,autocomplete,Javascript,Google Maps,Reactjs,Google Maps Api 3,Autocomplete,我在React应用程序中使用google maps autocomplete,但我在componentwillUnmount生命周期事件中遇到错误,即: this.autocomplete.removeListener不是函数 当我回到组件时,我得到以下错误: 您已多次在此页面上包含Google Maps API。 这可能会导致意外错误 在使用devtools检查页面元素时,似乎有多个脚本标记包含* 添加到html页面的页眉 如果我注释掉组件中的this.autocomplete.removeL
this.autocomplete.removeListener('place_changed')
,则将从主体中卸载脚本标记,但所有头脚本标记将保留。如果我取消注释同一行,那么即使是我附加在组件装载生命周期上的body脚本标记也会保留,并创建一个新的
componentDidMount () {
this.script = document.createElement('script')
this.script.src = `https://maps.googleapis.com/maps/api/js?key=${googleMapsAPIKey}&libraries=places`
this.script.async = 1
this.script.defer = 1
this.script.onload = () => this.initAutocomplete()
this.script.onerror = () => this.initAuthcompleteFailed()
document.body.appendChild(this.script)
}
componentWillUnmount () {
this.autocomplete.removeListener('place_changed')
// google.maps.event.clearInstanceListeners(this.autocomplete)
// console.log('THIS SCRIPT: ', this.script)
document.body.removeChild(this.script)
}
initAutocomplete () {
console.log('Google Maps Loaded')
this.autocomplete = new google.maps.places.Autocomplete(this._input.input, {types: ['geocode']})
this.autocomplete.addListener('place_changed', this.handlePlaceChanged)
this.geolocate()
}
initAuthcompleteFailed () {
console.log('Google Maps Loadeding Error')
}
错误“您在此页面上多次包含Google Maps API。这可能会导致意外错误。”如果您的网页多次包含Maps API,则会发生此错误。请检查是否有一个.js文件也在调用maps api。您可以在GitHub上检查此问题以及此相关错误。如果您的网页多次包含地图API,则会发生错误“您已在此页面上多次包含谷歌地图API。这可能会导致意外错误。”。请检查是否有一个.js文件也在调用maps api。您可以在GitHub上检查这一点,并将其与此相关。