如何在 运行 获取之前等待值?

How to wait for value before running fetch?

编辑:我最终使用了 axios 而不是 fetch,而且效果很好。刚刚删除了 response.json() 并将获取切换为 axios.get.

我的第一个 post 问题可能很简单。在输入 URL 之前,我试图让纬度和经度值成为实际值。大多数时候,我会收到错误请求返回的错误,因为纬度和经度值尚未传播。

谢谢!

代码在这里(编辑掉 API 键):

    const fetchData = async () => {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLat(position.coords.latitude);
        setLong(position.coords.longitude);
      });


      const url =
        await `https://api.openweathermap.org/data/2.5/weather/?lat=${lat}&lon=${long}&units=metric&APPID=DELETED`;
     
      await fetch(url)
        .then((response) => {
          return response.json();
        })
        .then((result) => {
          setData(result);
        })
        .catch(console.error);
    };

    fetchData();
  }, [lat, long]);


似乎在使用它们的useEffect中设置了纬度和经度。在另一个 useEffect 中使用它们之前,您可能应该设置它们。

useEffect(() => {
      navigator.geolocation.getCurrentPosition(function (position) {
        setLat(position.coords.latitude);
        setLong(position.coords.longitude);
      });
}, [])

useEffect(() => {
  const fetchData = async () => {

      const url = `https://api.openweathermap.org/data/2.5/weather/?lat=${lat}&lon=${long}&units=metric&APPID=DELETED`;
     
      await fetch(url)
        .then((response) => {
          return response.json();
        })
        .then((result) => {
          setData(result);
        })
        .catch(console.error);
    };

    if (lat && long) {
      fetchData();
    }
  }, [lat, long]);

要么必须将这些值存储在函数中,要么必须等到状态更新。状态是异步的,这就是您收到此错误的原因。