小编est*_*in8的帖子

如何在运行 fetch 之前等待值?

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

我在这里发表的第一篇文章可能是一个非常简单的问题。我试图在将纬度和经度值输入 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]);


Run Code Online (Sandbox Code Playgroud)

fetch reactjs

3
推荐指数
1
解决办法
469
查看次数

标签 统计

fetch ×1

reactjs ×1