JeromeD3 / react-hooks

my hooks
0 stars 0 forks source link

useRequest缓存 --- SWR #1

Open JeromeD3 opened 1 year ago

JeromeD3 commented 1 year ago

主要记录学习useRequest

JeromeD3 commented 1 year ago
JeromeD3 commented 1 year ago

SWR

- swr 实际上是 Cache Control 中新增的一个试验性指令

- Cache-Control: max-age=86400, stale-while-revalidate=172800

一句话概括,就是设置了cacheKey后, 在组件第二次加载时,会优先返回缓存的内容,然后在背后重新发起请求

JeromeD3 commented 1 year ago

实现原理

主要是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;

cache.js

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,
  });
};

执行流程

  1. 主要也是创建了一个map用于存储数据。
  2. 插件内部实现了set和get两个方法,主要用户获取缓存和设置缓存。
  3. 然后在onBefore 这个钩子函数的时候判断是否有缓存,有则返回,无则返回空。
  4. 最后在onSuccess这个钩子函数中重新缓存。道理也很简单,我都请求成功了,肯定要缓存最新的数据。