我可以避免每次使用 React Router 导航到另一个页面时加载 GoogleMaps 吗?

问题描述 投票:0回答:0

我的网站是一个基于 React Router 的 SPA。

我使用 Google Maps JS API 在我网站的一个页面中显示地图。我使用官方的加载方式:我在 DOM 中添加了一个带有回调函数的 GoogleMaps 脚本,这个回调函数加载地图并将其存储在状态中。

我的问题:当用户从一个页面导航到另一个页面时,React Router 卸载页面组件。因此,每次用户返回地图页面时都会触发 Google Maps API 加载。 Google 将此记录为 Maps API 的新用途,因此它将人为地增加 Google 对 API 的收费!

我的问题:有没有办法让我只启动一次 GoogleMaps API,并避免每次用户使用 React Router 从一个页面导航到另一个页面时卸载/重新加载它?

这是加载地图的页面的摘录。

  // A state is created to store the map object
  const [map, setMap] = useState(null)

  // The callback function executed by the GoogleMaps script when the map is loaded
  function initMap() {
    const map = new window.google.maps.Map(document.getElementById("map"), mapOptions)
    setMap(map)
    /* Many other things such as :
    - setting listeners
    - adding markers to the map
    */
  }
  window.initMap = initMap;

  // The script tag is added to the DOM
  // It must not be added before the initMap function is defined, so we add it this way rather than writing the script in index.html
  var script = document.createElement('script');
  script.id="myscript"
  script.src = 'https://maps.googleapis.com/maps/api/js?key=MMY_API_KEY&callback=initMap';
  script.async = true

  useEffect(() => {
    const scriptElement = document.getElementById("myscript");
    document.head.appendChild(script);
  },[])

  // All GoogleMaps scripts previously writen in the DOM are deleted when the component is unmounted and google is set to {}, to avoid multiple loadings
  useEffect(() => {
    return () => {
      let existingScript = document.getElementById("myscript")
      if (existingScript) {
        existingScript.remove()
      }
      window.google = {}
    }
  }, [])

  return (
    <Fragment>
      <div style={{ width: "100%", height: "100%" }} id="map"/> 
      {/* And other JSX objects*/}
    </Fragment>
  )
reactjs google-maps
© www.soinside.com 2019 - 2024. All rights reserved.