"Google Maps JavaScript API multiple times" 将 react-google-maps 与 react-places-autocomplete 结合使用时出错

"Google Maps JavaScript API multiple times" error when using react-google-maps with react-places-autocomplete

我正在使用 react-google-maps which requires a googleMapURL prop on it's component (which declares Google Maps JavaScript API) and react-places-autocomplete,它也需要带有 google 地图 js API 的脚本。

当我同时执行这两项操作时,出现错误 "You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors"。

我不能不声明 react 道具,否则组件将无法工作,如果我不在 index.html 中声明脚本,react-places-autocomplete 将无法工作。

如何在使用这两个库时不出现此错误?

我在 create-react-app 项目的 public 文件夹内的 index.html 声明这个脚本 <script type="text/javascript"src="https://maps.googleapis.com/maps/api/js?key=MY_KEY_HERE&libraries=places"></script>

并且还声明 google 映射 api 的组件如下

<WrappedMap
   googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${googleMapAPIKey}&v=3.exp&libraries=geometry,drawing,places`}
   loadingElement={<div className={styles.map} />}
   containerElement={<div className={styles.map} />}
   mapElement={<div className={styles.map} />}
/>

在 Leigh Halliday 的 youtube 频道询问后,我得到了答案。您可以将 react-google-maps 与一个名为 withGoogleMap 的高阶组件一起使用,它看起来假设您已经在您网站的其他地方安装了 google 地图脚本。 https://tomchentw.github.io/react-google-maps/#withgooglemap