You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native:缓存还是本地存储?每日调用一次国家API方案咨询

方案对比与实现指南

需求回顾

调用外部国家API获取详情,要求24小时内同一用户仅调用一次;APP启动时判断:24小时内复用本地数据,超过24小时则重新请求API。


方案1:基于react-native-mmkv手动实现缓存过期

无需主动“清除”本地存储,通过存储过期时间戳判断数据有效性即可,核心逻辑如下:

实现思路

  1. 首次请求API后,将国家数据与「当前时间+24小时」的过期时间戳一同存入MMKV
  2. 每次需要数据时,先读取存储的过期时间与数据
  3. 对比当前时间与过期时间:未过期则直接用本地数据,过期则重新请求并更新存储内容

代码示例

import { MMKV } from 'react-native-mmkv';

// 初始化MMKV实例(单独命名空间避免冲突)
const countryStorage = new MMKV({ id: 'country-cache' });

// 存储国家数据及过期时间
const saveCountryData = (data) => {
  const expireTimestamp = Date.now() + 24 * 60 * 60 * 1000; // 计算24小时后的时间戳
  countryStorage.set('countries', JSON.stringify(data));
  countryStorage.set('countries_expire', expireTimestamp.toString());
};

// 获取有效国家数据
const getValidCountryData = () => {
  const expireStr = countryStorage.getString('countries_expire');
  const storedData = countryStorage.getString('countries');

  if (!expireStr || !storedData) return null;

  const expireTimestamp = parseInt(expireStr, 10);
  if (Date.now() < expireTimestamp) {
    // 数据未过期,返回解析后的本地数据
    return JSON.parse(storedData);
  } else {
    // 数据过期,清理旧存储(可选,下次存储会自动覆盖)
    countryStorage.delete('countries');
    countryStorage.delete('countries_expire');
    return null;
  }
};

// 业务侧调用逻辑
const fetchCountries = async () => {
  const localData = getValidCountryData();
  if (localData) return localData;

  // 过期或无本地数据,发起API请求
  const res = await fetch('https://your-country-api-endpoint');
  const apiData = await res.json();
  saveCountryData(apiData);
  return apiData;
};

方案2:使用缓存库实现

借助成熟的缓存库(如axios-cache-adapter、react-native-cache),这类库已封装好过期判断、缓存管理逻辑,无需手动处理时间戳。

示例:axios-cache-adapter配合MMKV(适配已有MMKV依赖)

import axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
import { MMKV } from 'react-native-mmkv';

// 自定义MMKV存储适配器,适配缓存库的存储接口
class MMKVStore {
  constructor() {
    this.store = new MMKV({ id: 'api-cache' });
  }

  get(key) {
    return this.store.getString(key);
  }

  set(key, value) {
    this.store.set(key, value);
  }

  delete(key) {
    this.store.delete(key);
  }
}

// 配置缓存规则:24小时过期,使用MMKV作为存储介质
const cache = setupCache({
  maxAge: 24 * 60 * 60 * 1000,
  store: new MMKVStore()
});

// 创建带缓存能力的axios实例
const apiClient = axios.create({ adapter: cache.adapter });

// 调用API时自动触发缓存逻辑
const fetchCountries = async () => {
  const res = await apiClient.get('https://your-country-api-endpoint');
  return res.data;
};

方案对比与推荐

维度MMKV手动实现缓存库实现
代码复杂度需手动处理时间戳、存储逻辑封装完善,代码简洁
灵活性完全自定义,适配特殊需求需遵循库的规则,定制成本高
依赖数量仅依赖MMKV需额外引入缓存库
出错概率易因时间戳处理等细节出错成熟库,bug概率低

推荐结论

如果需求仅为简单的24小时过期缓存,优先选择缓存库方案——节省开发时间,降低手动编码的出错风险。如果项目已重度依赖MMKV且不想引入额外依赖,或需要自定义特殊缓存规则(比如结合其他条件触发失效),则手动实现方案更合适。

内容的提问来源于stack exchange,提问作者amitshree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:07:39