如何将此代码转换为 async wait 语法?(反应本机)

我正在尝试通过尝试将此代码转换为它来学习如何使用异步等待。有人可以指导我完成它吗?


const fetchWeather = () => {

    fetch(

      "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***"

    )

      .then((res) => res.json())

      .then((json) => {

        setData({ data: json });

        setTemp({ temp: (json.main.temp - 273.15).toFixed(2) + " C" });

        setCityDisplay({ cityDisplay: json.name });

        setIcon({ icon: json.weather[0].icon });

        setMain({ main: json.weather[0].main });

        setHumidity({ humidity: json.main.humidity + " %" });

        setPressure({ pressure: json.main.pressure + " hPa" });

        setVisibility({

          visibility: (json.visibility / 1000).toFixed(2) + " km",

        });

      })

      .catch((err) => console.warn(err));

  };

到目前为止我有这个:


async function fetchWeatherr() {

    try {

      const response = (

        await fetch(

          "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***"

        )

      ).json();

    } catch (err) {

      console.warn("error");

    }

  }

但我不确定是否应该使用像 useEffect 这样的钩子


宝慕林4294392
浏览 55回答 1
1回答

翻过高山走不出你

你可以这样做async function fetchWeatherr() {  try {    const response = await fetch(      'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=***'    );    const json = await response.json();    setData({ data: json });    setTemp({ temp: (json.main.temp - 273.15).toFixed(2) + ' C' });    setCityDisplay({ cityDisplay: json.name });    setIcon({ icon: json.weather[0].icon });    setMain({ main: json.weather[0].main });    setHumidity({ humidity: json.main.humidity + ' %' });    setPressure({ pressure: json.main.pressure + ' hPa' });    setVisibility({      visibility: (json.visibility / 1000).toFixed(2) + ' km',    });  } catch (err) {    console.warn('error');  }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript