如何从 UseEffect Hook 返回值返回值、UseEffect、Hook

2023-09-06 18:46:57 作者:恋人手心

我从使用效果钩子(我相对较新)中获取纬度和经度.我想返回使用效果钩子之外的值,并将它们存储在变量中,如果需要的话甚至存储在状态中.我可以控制台记录这些值,但我只是添加一个返回语句还是以某种方式传递参数?我需要使用什么功能?我计划将 lat 和 long 数据传递到代码的其他部分,这就是我尝试从 useEffect 挂钩中检索它的原因.

I am getting the latitude and longitude from a Use Effect hook (which I am relatively new to). I want to return the values outside the use effect hook and store them in variables or even state if needed. I can console log the values but do i just add a return statement or pass arguments somehow? What feature do i need to make use of? I plan to pass the lat and long data into other parts of code which is why i am trying to retrieve it from the useEffect hook.

useEffect(() => {
    if ("geolocation" in navigator) {
      console.log("Available");
    } else {
      console.log("Not Available");
    }
    navigator.geolocation.getCurrentPosition(function (position) {
      let lat = position.coords.latitude;
      let long = position.coords.longitude;
      console.log(lat);
      console.log(long);
    });
  }, []);

let newLat = lat?
let newLong = long?

推荐答案

您可以将它们保存在状态或引用挂钩中.

You can save them in a state or a reference hook.

以下是我将如何使用参考挂钩:

Here is how I would do it with a reference hook:

const lat = useRef(null);
const long = useRef(null);

useEffect(() => {
    if ("geolocation" in navigator) {
      console.log("Available");
    } else {
      console.log("Not Available");
    }
    navigator.geolocation.getCurrentPosition(function (position) {
      lat.current = position.coords.latitude;
      long.current = position.coords.longitude;
      console.log(lat);
      console.log(long);
    });
  }, []);

然后您可以使用 .current 访问 latlong 值.更改它们不会触发重新渲染.

You can then access the lat and long values using .current on them. Changing them will not trigger a re-render.

如果你想使用状态,你可以这样做

If you want to use states you can do it like this

const [lat, setLat] = useState(null);
const [long, setLong] = useState(null);

useEffect(() => {
    if ("geolocation" in navigator) {
      console.log("Available");
    } else {
      console.log("Not Available");
    }
    navigator.geolocation.getCurrentPosition(function (position) {
      setLat(position.coords.latitude);
      setLong(position.coords.longitude);
      console.log(lat);
      console.log(long);
    });
  }, [setLat, setLong]);

您可以像使用任何正常状态一样使用它们.

And you can use them like any normal state.

在尝试使用它们时,还要确保它们的值不为空.

Also make sure that their values are not null when trying to use them.