Reactjs 在react应用程序上刷新和重新蚀刻api的最佳方法
我正在构建一个简单的react应用程序,从OpenWeatherAPI获取数据。我想每分钟刷新收到的数据,以反映应用程序的更改(如果有任何更改)。我在调用我创建的fetchApi函数时尝试使用setInterval,但根据控制台日志,它听起来不太精确或不可靠。这是我的部分代码:Reactjs 在react应用程序上刷新和重新蚀刻api的最佳方法,reactjs,async-await,Reactjs,Async Await,我正在构建一个简单的react应用程序,从OpenWeatherAPI获取数据。我想每分钟刷新收到的数据,以反映应用程序的更改(如果有任何更改)。我在调用我创建的fetchApi函数时尝试使用setInterval,但根据控制台日志,它听起来不太精确或不可靠。这是我的部分代码: useEffect(() => { const currentData = async () => { const currentWeatherData = await fetchCurrentD
useEffect(() => {
const currentData = async () => {
const currentWeatherData = await fetchCurrentData();
setCurrentWeather(currentWeatherData);
};
const futureData = async () => {
setFutureWeather(await fetchFutureData())
console.log(futureWeather);
};
currentData();
futureData();
setInterval(() => {
currentData();
futureData();
console.log("reloaded!");
}, 60000);
}, []);
如何改进此代码以使其有效工作?
谢谢大家我想您需要在清除useffect函数时清除间隔
useEffect(() => {
const currentData = async () => {
const currentWeatherData = await fetchCurrentData();
setCurrentWeather(currentWeatherData);
};
const futureData = async () => {
const futureWeatherData = await fetchFutureData();
setFutureWeather(futureWeatherData);
};
currentData();
futureData();
const intervalId = setInterval(() => {
currentData();
futureData();
}, 60000);
return () => {
clearInterval(intervalId);
};
}, []);
您可能希望在返回函数中从
useffect
清除该间隔。现在刷新需要一分钟以上的时间。setInterval可能会在开始时等待一分钟以启动函数?您首先运行fetch函数,然后再运行setInterval
,然后每1分钟触发一次。您应该检查devtools中的network
选项卡以了解发生了什么。问题是如果我没有在setInterval之前调用这两个函数,那么在调用函数之前一分钟内都不会有结果