使用缓存减少网络请求

先交待下背景,在动态表单中,客户标签数据数据来源于服务器,每次添加一项时,客户标签组件都会请求服务器获取待标签列表,当频繁添加项的时候就会频繁的发送网络请求

如何减少网络请求?普遍是思路是将获取的数据缓存到本地,待以后使用,为了保持数据的新鲜性,可以设置一个合理的“保鲜期”,当缓存过期时重新请求最新的数据。如下图

下面来写一段伪代码

function A (){
  // .... 
  // ....
  function getData(){
    //获取数据,并且设置缓存
  }
  useEffect(()=>{
    // 如果有缓存
    if(xx){
      // 判断是否过期
      // 如果过期则请求
      getData();
    }else{
      // 如果没有缓存则请求
      getData();
    }
  },[]);
}
复制代码

这样一看感觉挺好,基本实现了我们想要的功能,但是有一个问题,在每个组件内都需要写一段更新缓存的代码,我们还需要将更新缓存的逻辑提取出来,首先设计一下方案,我们需要三个基础的要素:

  1. 请求函数
  2. 缓存对应的key,用于读写缓存
  3. 缓存有效期

依照上面的思路和这三个要素,我写了一版React Cache Hook

// 多处使用相同数据时,第一次时从服务端获取数据,其后则从SessionStorage中获取数据
import { useEffect } from "react";
import { useSessionStorageState, useRequest } from "ahooks";
const useCache = <T>(api: () => void, key: string, expires = 10000) => {
  const [cache, setCache] = useSessionStorageState<{
    createTime: string,
    data: T
  }>(key);
  const { run, data } = useRequest(api, { manual: true });
  useEffect(() => {
    if (data) {
      setCache({ createTime: new Date().toString(), data: data.data });
    }
  }, [data]);
  useEffect(() => {
    if (cache) {
      const createTime = new Date(cache.createTime || "");
      const time = new Date().getTime() - createTime.getTime();
      if (time > expires) {
        run();
      }
    } else {
      run();
    }
  }, []);
  return [cache?.data];
};
export default useCache;
复制代码

调用很简单

import useCache from "@/hooks/useCache";
//...
const index = (props: Props) => {
  const [list] = useCache<Array<Tag>>(getTagList, "customerTags");
}
//...
export default index;
复制代码

猜你喜欢

转载自juejin.im/post/7107536636296036388