亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將此代碼轉換為 async wait 語法?(反應本機)

如何將此代碼轉換為 async wait 語法?(反應本機)

寶慕林4294392 2023-12-14 16:55:19
我正在嘗試通過嘗試將此代碼轉換為它來學習如何使用異步等待。有人可以指導我完成它嗎?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 這樣的鉤子
查看完整描述

1 回答

?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

你可以這樣做


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

  }

}


查看完整回答
反對 回復 2023-12-14
  • 1 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號