ReactJS定时API请求:如何将setInterval值传入清理函数
问题描述
进入CurrencyPage页面时,我尝试从数据库获取currencyConversionRates列表,随后设置定时器每隔6秒获取更新后的列表。目前功能正常,但无法将setInterval的返回值传入清理函数,返回值始终为Promise格式:
Promise {<fulfilled>: 1}
如何将setInterval值传入清理函数,确保导航至其他页面时停止定时器执行?
原useEffect代码
useEffect(() => { const getCurrencyConversionRates=async()=>{ console.log("Retrieving list of currency conversion rate"); await retrieveCurrencyConversionRateFunction(); //Gets new information every 6 seconds const intervalCall = setInterval(async() => { console.log("Getting new currency conversion rates!"); const currTime = new Date().toLocaleTimeString(); console.log("Time -> "+currTime); await retrieveCurrencyConversionRateFunction(); }, 60*100); //Have to wait until currencyConversionRateFunction is loaded before the map function is called on it in the render view otherwise will have error setLoading(false); return intervalCall; } let intervalCall = getCurrencyConversionRates(); //Clear interval return () => { console.log("CLEARING CURRENCY INTERVAL HERE"); console.log(intervalCall); clearInterval(intervalCall); }; },[]);
解决方案(基于Azzy的回答)
无需在getCurrencyConversionRates()中返回定时器,可在函数外初始化变量存储setInterval创建的定时器。
提示:无法通过参数按引用传递变量给getCurrencyConversionRates(),因为变量修改不会保存。但在JavaScript中,可在函数外初始化变量并在函数内修改其值。
修改后的代码:
useEffect(() => { const getCurrencyConversionRates=async()=>{ // console.log("Retrieving list of currency conversion rate"); await retrieveCurrencyConversionRateFunction(); //Gets new information every 6 seconds intervalCall = setInterval(async() => { // console.log("Getting new currency conversion rates!"); const currTime = new Date().toLocaleTimeString(); console.log("Time -> "+currTime); await retrieveCurrencyConversionRateFunction(); }, 60*100); //Have to wait until currencyConversionRateFunction is loaded before the map function is called on it in the render view otherwise will have error setLoading(false); // return intervalCall; } let intervalCall; getCurrencyConversionRates(); //Clear interval return () => { console.log("CLEARING CURRENCY INTERVAL HERE"); console.log(intervalCall); clearInterval(intervalCall); }; },[]);
内容的提问来源于stack exchange,提问作者Yeo Bryan
相关产品推荐
相关产品推荐

