Reactjs 您已经多次调用谷歌地图API
我有一个试剂组件,当它安装时,我导出一个名为loadMap的函数: google_maps.jsReactjs 您已经多次调用谷歌地图API,reactjs,google-maps-api-3,clojurescript,reagent,Reactjs,Google Maps Api 3,Clojurescript,Reagent,我有一个试剂组件,当它安装时,我导出一个名为loadMap的函数: google_maps.js export function loadMap() { // Create the script tag, set the appropriate attributes var script = document.createElement('script'); script.src = 'https://maps.googleapis.com/maps/api/js?key
export function loadMap() {
// Create the script tag, set the appropriate attributes
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
script.defer = true;
script.async = true;
// Attach your callback function to the `window` object
window.initMap = function() {
console.log("init map");
console.log("Element is ", document.getElementById("map") )
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8
});
};
// Append the 'script' element to 'head'
document.head.appendChild(script);
}
像这样:
import loadMap from "google_maps.js"
控制台正在打印回调函数的日志,但也显示以下内容:
You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
cj @ js?key=API_KEY&callback=initMap:138
ij @ js?key=API_KEY&callback=initMap:135
google.maps.Load @ js?key=API_KEY&callback=initMap:14
(anonymous) @ js?key=API_KEY&callback=initMap:227
(anonymous) @ js?key=API_KEY&callback=initMap:227
地图上没有显示
--编辑--
clojurescript导入
["./google_maps.js" :refer (loadMap)]
用法:
[load-map
[:div {:id "map"}]
]
如果要在基于类的组件的
render()
方法内部或功能组件的return
语句内部创建script
元素,则将在状态更新时多次创建脚本
为了只创建一次script
元素,可以将它放在onMount()
生命周期方法中,或者使用useffect()
钩子
您可以将函数传递到useffect()
钩子中,如下所示:
import {useEffect} from "react"
import loadMap from "google_maps.js";
const App = () => {
useEffect(loadMap, [])
return (
.....
.....
.....
)
}
这应该只在组件装载时呈现脚本
元素一次。如果您需要在另一个时间点呈现它,请考虑查看其他生命周期方法和钩子。
只要小心访问
文档
。React通常不能很好地处理像那样的直接访问和操作。如果在基于类的组件的render()
方法内部或在功能组件的return
语句内部创建script
元素,则最好尝试使用refs
并使用JSX而不是普通的Javascript API呈现元素。<,然后,脚本将在状态更新时创建多次
为了只创建一次script
元素,可以将它放在onMount()
生命周期方法中,或者使用useffect()
钩子
您可以将函数传递到useffect()
钩子中,如下所示:
import {useEffect} from "react"
import loadMap from "google_maps.js";
const App = () => {
useEffect(loadMap, [])
return (
.....
.....
.....
)
}
这应该只在组件装载时呈现脚本
元素一次。如果您需要在另一个时间点呈现它,请考虑查看其他生命周期方法和钩子。
只要小心访问
文档
。React通常不能很好地处理像那样的直接访问和操作。最好尝试使用refs
并使用JSX呈现元素,而不是使用普通的Javascript API。https://maps.googleapis.com/maps/api/您在网络面板中看到了吗?在何处执行loadMap()?它不起反应。检查编辑。我看到initMap控制台日志两次。请不要在公共站点上共享私有API密钥,并确保根据以下限制它们:https://maps.googleapis.com/maps/api/
您在网络面板中看到了吗?在何处执行loadMap()?它不起反应。检查编辑。我看到initMap控制台日志两次。请不要在公共站点上共享私有API密钥,并确保按照以下要求限制它们: