【发布时间】:2021-11-20 16:17:44
【问题描述】:
伙计们,我正在开发天气应用程序,但我与 useState 异步作斗争。我在 stackoverflow 上读到它可以通过 useState 函数中的回调来解决。所以我试过了,但没有任何改变。问题是当我点击提交按钮时,状态必须从 API 接收数据,但它没有成功,我的状态为空。出了什么问题,如果你能根据我的代码帮助我。 P.S 遗漏了一些不重要的功能
const useForecast = () => {
const [forecast, setForecast] = useState(null);
const gatherForecastData = async data => {
const currentDay = await getCurrentDayForecast(data.consolidated_weather[0], data.title);
const currentDayDetails = await getCurrentDayDetailedForecast(data.consolidated_weather[0]);
await setForecast(() => {
return { currentDay, currentDayDetails};
});
setLoading(false);
};
// MAIN FUNC AND TROUBLE IS HERE
const submitRequest = async location => {
setLoading(true);
setError(false);
const response = await getWoeid(location);
if (!response?.woeid) return;
const data = await getForecastData(response.woeid);
if (!data) return;
await gatherForecastData(data);
console.log(data);
// DATA SHOWS OK
console.log(forecast);
// SHOWS INITIAL STATE FOR THE FIRST SUBMIT
};
}
【问题讨论】:
标签: javascript reactjs react-hooks