【问题标题】:setState from another functional component ReactJS来自另一个功能组件 ReactJS 的 setState
【发布时间】:2021-06-03 15:12:07
【问题描述】:

我刚从 react 类学习,开始研究钩子和功能组件。 我有这段代码可以加载地图脚本

let autoComplete;
// dynamically load JavaScript files in our html with callback when finished
const loadScript = (url, callback) => {
  let script = document.createElement("script"); // create script tag
  script.type = "text/javascript";

  // when script state is ready and loaded or complete we will call callback
  if (script.readyState) {
    script.onreadystatechange = function () {
      if (script.readyState === "loaded" || script.readyState === "complete") {
        script.onreadystatechange = null;
        callback();
      }
    };
  } else {
    script.onload = () => callback();
  }

  script.src = url; // load by url
  document.getElementsByTagName("head")[0].appendChild(script); // append to head
};

// handle when the script is loaded we will assign autoCompleteRef with google maps place autocomplete
function handleScriptLoad(updateQuery, autoCompleteRef) {
  // assign autoComplete with Google maps place one time
  autoComplete = new window.google.maps.places.Autocomplete(
    autoCompleteRef.current,
    {
      types: ["establishment"],
      strictBounds: true,
      fields: ["address_components", "name", "geometry"],
      componentRestrictions: { country: "us" },
    }
  );
  autoComplete.setFields(["address_components", "formatted_address"]); // specify what properties we will get from API
  // add a listener to handle when the place is selected
  autoComplete.addListener("place_changed", async () => {
    handlePlaceSelect(updateQuery);
  });
}

我需要从下面的函数中设置状态或更新状态,只是它不是保持状态的主函数

function handlePlaceSelect(updateQuery) {
  const [coodinates, setCoordinates] = useState({
    lat: null,
    lng: null,
  });

  const addressObject = autoComplete.getPlace(); // get place from google api
  const query = addressObject.formatted_address;
  updateQuery(query);
  var address = "";
  if (addressObject.address_components) {
    address = [
      (addressObject.address_components[0] &&
        addressObject.address_components[0].short_name) ||
        " , ",
      (addressObject.address_components[1] &&
        addressObject.address_components[1].short_name) ||
        " , ",
      (addressObject.address_components[2] &&
        addressObject.address_components[2].short_name) ||
        " , ",
    ].join(", ");
  }
  var completeAddress = addressObject.name + ", " + address;
  console.log(completeAddress);
  console.log("Latitude: " + addressObject.geometry.location.lat());
  console.log("Longitude: " + addressObject.geometry.location.lng());

  /// heres where am trying to update state of coordinates when a place is changed
 setCoordinates({
   lat: addressObject.geometry.location.lat(),
   lng: addressObject.geometry.location.lng()

 })
} 

下面的主要功能是加载useeffect中的地图脚本

function Storelocation({ setTab }) {
  const [query, setQuery] = useState("");

  const autoCompleteRef = useRef(null);

  const [address, setAddress] = React.useState("");
  const [coordinates, setCoordinates] = React.useState({
    lat: null,
    lng: null
  });

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

return (
 <input
              className=""
              required
              placeholder="address"
              ref={autoCompleteRef}
              onChange={(event) => {
                setQuery(event.target.value)
              }}
             defaultValue={query}
            ></input>

);
}

如何使用这种方式更新状态,即从另一个函数更新它

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您可以将 statefull 组件中的函数传递给您的子组件,该子组件使用 setState 为您管理状态更改。

    【讨论】:

    • 你能解释更多并可能重构代码
    • 我可以稍后再做 :)
    • ` useEffect(() => { loadScript(https://maps.googleapis.com/maps/api/js?key=AIzaSyCT2wFvkG_abY&amp;libraries=places, () => handleScriptLoad(setQuery, autoCompleteRef)); }, []); ` 你应该传递一个handleQuery 并在状态所在的地方使用setQuery 而不是setQuery。大概就这样吧,不然我晚上有更多的时间。
    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多