首页 > 解决方案 > 如何将此代码转换为异步等待语法?(反应原生)

问题描述

我试图通过尝试将这段代码转换为它来学习如何使用异步等待。请有人指导我完成它。

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 这样的钩子

标签: javascriptreactjsreact-native

解决方案


你可以这样做

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');
  }
}

推荐阅读