JeromeD3 / react-hooks

my hooks
0 stars 0 forks source link

useRequest缓存 --- 自定义缓存 #5

Open JeromeD3 opened 1 year ago

JeromeD3 commented 1 year ago

有的时候我们不想让数据缓存在一个map中,想通过配置 setCache 和 getCache,可以自定义数据缓存,比如可以将数据存储到 localStorage、IndexDB 等。

JeromeD3 commented 1 year ago

新增代码

useCachePlugin

import * as cache from '../utils/cache';
import useCreation from '../../../useCreation';
const useCachePlugin = (fetchInstance, {
  cacheKey,
  staleTime = 0,
+ cacheTime = 5 * 60 * 1000,
+ setCache: customSetCache,
+ getCache: customGetCache
}) => {
  const _setCache = (key, cachedData) => {
+    if (customSetCache) {
+      customSetCache(cachedData);
+    } else {
       cache.setCache(key, cacheTime, cachedData);
+    }
  };

  const _getCache = (key, params) => {
+   if (customGetCache) {
+     return customGetCache(params);
+   }
    return cache.getCache(key);
  };
JeromeD3 commented 1 year ago

实现原理

  1. 主要也是传递三个参数,缓存时间,自定义的获取缓存函数和设置函数
  2. 然后走一下判断,如果有自定义的走自定义,没有就缓存在map