【发布时间】:2021-07-01 02:55:12
【问题描述】:
我在使用 google maps js API 时遇到错误,每隔几次加载我都会收到此错误。
TypeError:无法读取未定义的属性“地图” (匿名函数) src/features/landingPage/components/LandingPageMap.js:10
地图组件
const LandingPageMap = (props) => {
const { center, zoom, reports } = props;
const mapRef = useRef();
useEffect(() => {
const map = new window.google.maps.Map(mapRef.current, {
center: center,
zoom: zoom,
disableDefaultUI: true,
});
}, [center, zoom, reports]);
return (
<>
<div
ref={mapRef}
className={`map ${props.className}`}
style={props.style}
>
Loading map...
</div>
</>
);
};
export default LandingPageMap;
我在 head 标签内的 index.html 文件中获取 Google 地图 API。
<script async
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE-MAPS-API-KEY&libraries=places&callback=initMap">
</script>
我不知道如何解决这个问题。感谢您的时间和帮助。
【问题讨论】:
-
您可以在尝试使用之前检查
window.google是否存在。if (window.google) { //do stuff }这将防止致命错误,但您可能并不总是有地图。 -
@LindaPaiste 我试过了,但不幸的是,它没有解决问题。
标签: reactjs google-maps