Open JeromeD3 opened 1 year ago
我们可以看到ahooks的案例,input框为需要缓存的参数
然后我们查看源代码,input绑定的state
是来自于useRequest
返回的params
参数,说明useRequest对上一次传递的参数进行了缓存,那这个情况该如何实现呢?
新增代码如下:
import * as cache from '../utils/cache';
+import useCreation from '../../../useCreation';
const useCachePlugin = (fetchInstance, {
cacheKey,
staleTime = 0,
}) => {
const _setCache = (key, cachedData) => {
cache.setCache(key, cachedData);
};
const _getCache = (key) => {
return cache.getCache(key);
};
+ useCreation(() => {
+ if (!cacheKey) {
+ return;
+ }
+ const cacheData = _getCache(cacheKey);
+ if (cacheData && Object.hasOwnProperty.call(cacheData, 'data')) {
+ fetchInstance.state.data = cacheData.data;
+ fetchInstance.state.params = cacheData.params;
+ if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) {
+ fetchInstance.state.loading = false;
+ }
+ }
+ })
if (!cacheKey) {
return {};
}
return {
onBefore: params => {
const cacheData = _getCache(cacheKey, params);
if (!cacheData || !Object.hasOwnProperty.call(cacheData, 'data')) {
return {};
}
if (staleTime === -1 || new Date().getTime() - cacheData.time <= staleTime) {
return {
loading: false,
data: cacheData?.data,
returnNow: true
};
} else {
return {
data: cacheData?.data
};
}
},
onSuccess: (data, params) => {
if (cacheKey) {
_setCache(cacheKey, {
data,
params,
time: new Date().getTime()
});
}
}
};
};
export default useCachePlugin;
我们从代码也可以清楚的看到,新增了useCreation这个hook。
keyword
本来会被初始化为初始值,但是我们有缓存staleTime
中,也就是需不需要在规定时间内重新请求,是则loading = false
,这样就给用户一种没有刷新的感觉setState
,那就是最初的值)
缓存的数据包括 data 和 params,通过 params 缓存机制,我们可以记忆上一次请求的条件,并在下次初始化。