React cache Google Places api搜索结果

问题描述

所以我有以下功能正常的组件。我想做的就是缓存结果,这样我就不会针对相同的搜索词一遍又一遍地敲击api。

import React,{ useState,useEffect,useRef } from "react";
import currentSession from "../currentSession";

let autoComplete;

const loadScript = (url,callback) => {
  let script = document.createElement("script");
  script.type = "text/javascript";

  if (script.readyState) {
    script.onreadystatechange = function () {
      if (script.readyState === "loaded" || script.readyState === "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = () => callback();
  }

  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
};

function handleScriptLoad(updateQuery,autoCompleteRef) {
  autoComplete = new window.google.maps.places.Autocomplete(
    autoCompleteRef.current,{ types: ["(cities)"] }
  );
  autoComplete.setFields(["address_components","formatted_address"]);
  autoComplete.addListener("place_changed",() =>
    handlePlaceSelect(updateQuery)
  );
}

async function handlePlaceSelect(updateQuery) {
  const addressObject = autoComplete.getPlace();
  const query = addressObject.formatted_address;
  updateQuery(query);
}

function SearchLocationInput(props) {
  const [query,setQuery] = useState("");
  const autoCompleteRef = useRef(null);

  useEffect(() => {
    loadScript(
      "https://maps.googleapis.com/maps/api/js?key=" +
        currentSession.getGoogleApiKey() +
        "&libraries=places",() => handleScriptLoad(setQuery,autoCompleteRef)
    );
  },[]);

  return (
    <div className="search-location-input">
      <input
        ref={autoCompleteRef}
        onChange={(event) => {
          props.onCityChange(event.target.value);
          setQuery(event.target.value);
        }}
        placeholder="Enter a City"
        value={query}
      />
    </div>
  );
}

export default SearchLocationInput;

我假设请求是在加载的脚本中发生的,所以我不确定该如何完成?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)