Open JeromeD3 opened 1 year ago
- swr 实际上是 Cache Control 中新增的一个试验性指令
- Cache-Control: max-age=86400, stale-while-revalidate=172800
一句话概括,就是设置了cacheKey
后, 在组件第二次加载时,会优先返回缓存的内容,然后在背后重新发起请求
主要是useCachePlguin
这个插件的实现 , 部分代码如下
import * as cache from '../utils/cache';
const useCachePlugin = (fetchInstance, {
cacheKey,
cacheTime = 5 * 60 * 1000, // 默认五分钟
}) => {
const _setCache = (key, cachedData) => {
cache.setCache(key, cachedData);
};
const _getCache = (key) => {
return cache.getCache(key);
};
if (!cacheKey) {
return {};
}
return {
onBefore: params => {
const cacheData = _getCache(cacheKey, params);
if (!cacheData || !Object.hasOwnProperty.call(cacheData, 'data')) {
return {};
}
return {
data: cacheData?.data
};
},
onSuccess: (data, params) => {
if (cacheKey) {
_setCache(cacheKey, {
data,
params,
time: new Date().getTime()
});
}
}
};
};
export default useCachePlugin;
const setCache = (key: any, cacheTime: number, cachedData: any) => {
const currentCache = cache.get(key);
if (currentCache?.timer) {
clearTimeout(currentCache.timer);
}
let timer: any = undefined;
if (cacheTime > -1) {
// if cache out, clear it
timer = setTimeout(() => {
cache.delete(key);
}, cacheTime);
}
cache.set(key, {
...cachedData,
timer,
});
};
onBefore
这个钩子函数的时候判断是否有缓存,有则返回,无则返回空。onSuccess
这个钩子函数中重新缓存。道理也很简单,我都请求成功了,肯定要缓存最新的数据。
主要记录学习useRequest