我的应用程序的一部分有一个地图部分,我不会自动加载它。因此,我在地图组件中加载 Bing Map SDK,并在父组件中使用延迟加载。问题是在 SDK 完全加载之前调用了 getDefaultMap 函数。我找到了一个 hacky 解决方案,但我确信有一个更好的解决方案。基本上,依赖项在我的 useEffect 中不断更新,直到来自 SDK 的全局变量 Microsoft 被完全加载并且它按预期工作。
const [libraryLoaded, setLibraryLoaded] = useState(0)
const getDefaultMap = () => {
var map = new Microsoft.Maps.Map("#myMap", {
center: new Microsoft.Maps.Location(37, -96),
zoom: 4.5,
})
}
const addLibrary = () => {
let script = document.createElement("script")
script.src =
"http://www.bing.com/api/maps/mapcontrol?key=bing_api_key"
script.async = true
script.defer = true
document.body.appendChild(script)
script.onload = () => {
setLibraryLoaded(1)
}
}
useEffect(() => {
if (libraryLoaded) {
try {
getDefaultMap()
} catch {
setLibraryLoaded(libraryLoaded + 1)
}
} else {
addLibrary()
}
}, [libraryLoaded])
我是如何尝试解决它的:
我尝试在 script.onload 之后调用该函数。我也尝试删除 script.async
const addLibrary = () => {
let script = document.createElement("script")
script.src =
"http://www.bing.com/api/maps/mapcontrol?key=bing_api_key"
script.async = true
script.defer = true
document.body.appendChild(script)
script.onload = () => {
getDefaultMap(()
}
}
我还尝试像 Bing 文档中那样添加包含回调参数的脚本标签
<script
type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?key=bing_api_key&callback=getDefaultMap'
async
defer
></script>
还尝试了模板文字
<script
type='text/javascript'
src=`http://www.bing.com/api/maps/mapcontrol?key=bing_api_key&callback=${getDefaultMap}`
async
defer
></script>
也尝试过 onLoad
<script
type='text/javascript'
src='http://www.bing.com/api/maps/mapcontrol?key=bing_api_key'
async
defer
onLoad={() => {
getDefaultMap()
}}
></script>