前端性能优化-请求数据缓存

313 阅读1分钟

业务场景:前端有一个下拉框中的数据由后端请求而来,我们只需要获取一次之后写入内存,下一次直接从内存中拿,避免重复请求

前端框架:React

以获取证件类型为例:

image-20220329153127659

代码实现

let cache;

export const useCardType = () => {
  const [typeList, setTypeList] = useState(cache);
  const pending = useRef<boolean>(false);
  
  const getCardTypeList = useCallBack(async () => {
    try {
      // 当没有缓存并且不在pending状态中才请求接口,pending是防止正在请求中时cache没值而被多次调用
      if (!cache && !pending) {
        pending.current = true;
        // 你获取证件类型的接口
        const res = await request()
        cache = res
        setTypeList(res)
        pending.current = false
      }
    } catch (error) {
      pending.current = false
    }
  },[])
  
  useEffect(() => {
    getCardTypeList()
  },[getCardTypeList])
  
  return {
    cardTypeList: typeList
  }
}