<p>我需要在React应用程序中每隔一个小时刷新Spotify令牌(Spotify令牌有效期为1小时)。我知道以下方法使用<strong>useEffect</strong>钩子和<strong>setInteral</strong></p>
<pre class="brush:php;toolbar:false;">useEffect(() => {
const interval = setInterval(() => {
//调用API逻辑
}, 3600);
return () => clearInterval(interval);
}, [user])</pre>
<p>但是当应用程序关闭并重新打开时,它会再次发出新的请求以获取令牌(即使旧令牌仍然有效)。因此,我正在尝试根据剩余到期时间来实现需要调用API以获取新令牌的功能。如何实现这个功能。</p>
<p>我还创建了一个函数,用于在过去的时间之后计算剩余到期时间</p>
<pre class="brush:php;toolbar:false;">export const calculateRemainingExpirationTime = expirationTime => {
const currentTime = new Date().getTime();
const newExpirationTime = new Date(expirationTime).getTime()
const remainingTime = newExpirationTime - currentTime
return remainingTime; //以毫秒为单位
};</pre>
<p>因此,当页面重新加载时,我需要计算剩余到期时间,然后基于该时间调用API,然后每隔1小时调用API以获取新令牌。</p>
<p><strong>我需要实现以下功能</strong></p>
<ol>
<li>当页面重新加载时,计算剩余时间并根据剩余时间调用API</li>
<li>每隔1小时调用API</li>
</ol><p><br /></p>
你需要将
过期时间持久化到localStorage或使用Redux-persist来保存//此间隔仅在用户未关闭应用程序时执行 useEffect(() => { const interval = setInterval(() => { //调用api逻辑 //将过期时间写入本地存储 localStorage.setItem("expir",value) }, 3600); return () => clearInterval(interval); }, [user])//获取在本地存储中写入/存储的过期时间 React.useEffect(() => { let mounted = true; const getToken = () => { if (mounted) { const expirationtime = localStorage.getItem("expir"); if (new Date() > new Date(Number(expirationtime))) { // 过期,获取新的令牌 } else { // 存在的令牌 } } }; getToken(); return () => { mounted = false; }; }, [user]);