如何从 UseEffect Hook 返回值

lac*_*che 4 arguments parameter-passing reactjs use-effect

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

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);
    });
  }, []);
Run Code Online (Sandbox Code Playgroud)
let newLat = lat?
let newLong = long?
Run Code Online (Sandbox Code Playgroud)

Mar*_*vić 6

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

以下是我使用参考钩子的方法:

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);
    });
  }, []);
Run Code Online (Sandbox Code Playgroud)

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

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

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]);
Run Code Online (Sandbox Code Playgroud)

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

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