import Taro from '@tarojs/taro';

const storage = {
  // 本地永久存储写入有效期,有效期内会取出来,失效后会清空。exp 是有效时间的毫秒数
  setLocalStorage(key: string, value: any, exp: number) {
    const tmpData = { data: value, exp, startTime: new Date().getTime() };
    Taro.setStorageSync(key, tmpData);
  },

  // 处理数据本地数据缓存返回
  handleLocalDataBack<T>(tmpData: any, key: string): T | undefined {
    let returnData: undefined;
    const date = new Date().getTime();
    // 如果有设置过期时间
    if (tmpData && tmpData.exp) {
      if (date - tmpData.startTime > tmpData.exp) {
        // 缓存过期,清除缓存,返回false
        Taro.removeStorageSync(key);
        returnData = undefined;
      } else {
        // 缓存未过期,返回值
        returnData = tmpData.data;
      }
    } else {
      returnData = tmpData;
    }
    return returnData;
  },
  // 移除所有的wx-mini过期的本地缓存
  removeAllWxMiniExp() {
    Taro.getStorageInfo({
      success: function (res) {
        const keys = res.keys;
        keys.forEach((key) => {
          storage.handleLocalDataBack(Taro.getStorageSync(key), key);
        });
      }
    });
  },
  // 移除所有的本地存储
  removeAllLocal() {
    Taro.clearStorageSync();
  },
  // 移除本地所有的过期的缓存
  removeAllLocalExp() {
    storage.removeAllWxMiniExp();
  },
  // 本地取出存储的值
  getLocalStorage: <T>(key: string) => {
    // 小程序需要写入全局变量
    const tmpData = Taro.getStorageSync(key) ? Taro.getStorageSync(key) : undefined;
    return storage.handleLocalDataBack<T>(tmpData, key);
  },
  // 本地删除存储
  removeLocalStorage(key: string) {
    // 小程序需要写入全局变量
    Taro.removeStorageSync(key);
  }
};

const useExpiredStorage = () => {
  return [
    {
      get: storage.getLocalStorage,
      set: storage.setLocalStorage,
      remove: storage.removeLocalStorage
    }
  ];
};

export default useExpiredStorage;

参数:

  • key:存储键名

  • value:要存储的值

  • exp:有效期(毫秒),例如 1小时 = 3600000

过期判断逻辑:

  • 当前时间 - 存储时间 > 过期时长 → 判定为过期

设计目的:
提供符合React Hooks使用习惯的API,返回一个包含三个方法的对象:

  • get(key):获取数据(自动处理过期)

  • set(key, value, exp):存储数据(带过期时间)

  • remove(key):删除指定数据

设计亮点

  • 自动过期处理:获取数据时自动校验有效期

  • 批量清理:removeAllLocalExp()可清理所有过期数据

  • 类型安全:使用TypeScript泛型保持类型

  • 兼容性:基于Taro API,支持多端运行

  • Hook封装:符合现代React开发模式

注意事项

  • 存储空间:实际存储的数据比原始值多约20字节(包含时间戳和过期时间)

  • 性能影响:removeAllLocalExp()会遍历所有key,数据量大时需谨慎使用

  • 时间同步:依赖客户端本地时间,若用户修改系统时间会影响过期判断

  • 使用限制:适用于中小型数据存储(小程序存储上限约10MB)

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐