javascript - 如何将此代码转换为异步等待语法?(反应原生)
问题描述
我试图通过尝试将这段代码转换为它来学习如何使用异步等待。请有人指导我完成它。
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 这样的钩子
解决方案
你可以这样做
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');
}
}
推荐阅读
- python - Yaml 文件以不一致的格式保存内容,带有额外的花括号`{}`
- wordpress - 如何将图像分配给特定的 Wordpress 页面
- c# - 如何在 xamarin 中使用 mvvm 为 CollectionView 绑定滚动的 EventHendler
- python-3.x - 从 umap-learn 开始,我得到 numba 错误'操作数必须是相同类型,得到(i32,i64)'
- reactjs - 没有大气数据的谷歌地图自动完成reactjs
- php - 通过 ID 获取媒体模型并使用它来制作可下载的 URL 不起作用
- vhdl - 如何减少重复过程(握手)的状态逻辑冗余?
- wcf - 远程计算机中的 WCF netTcpBinding 超出消息大小配额
- sql - 如何为以下查询编写 sql 语句?
- javascript - React Native:如何在 View 中添加变量?