React Native 本地缓存:react-native-mmkv

在web开发中,通常使用localstorage/sessionStorege等来做本地缓存。在React Native可以使用 react-native-mmkv

安装依赖:

bash 复制代码
yarn add react-native-mmkv

使用

ts 复制代码
import {MMKV, Mode} from 'react-native-mmkv';

export const storage = new MMKV({
  id: `user-${userId}-storage`,
  path: `${USER_DIRECTORY}/storage`,
  encryptionKey: 'da98s7das7d9a8s7d9as87',
  mode: Mode.MULTI_PROCESS,
  readOnly: false,
});

实践

我们创建一个 storage 模块,用来管理本地缓存

ts 复制代码
// src/storage/modules/userStorage.ts
import {MMKV} from 'react-native-mmkv';
import {ENCRYPTION_KEY} from '@env';

export const userStorage = new MMKV({
  id: 'user-storage',
  encryptionKey: ENCRYPTION_KEY,
});

创建一个入口文件导出

ts 复制代码
// src/storage/index.ts
export * from './modules/userStorage';

修改首页查看效果:

tsx 复制代码
import {HomeScreenProps} from '@/navigation/types';
import {Button, Text, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {API_URL} from '@env';
import {scale, ScaledSheet} from 'react-native-size-matters/extend';
import {userStorage} from '@/storage';
import {useMMKVString} from 'react-native-mmkv';

const HomeScreen = ({}: HomeScreenProps) => {
  // const token = userStorage.getString('token');
  const [token, setToken] = useMMKVString('token', userStorage);

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      <View style={styles.content}>
        <Text style={{fontSize: scale(16)}}> HomeScreen {API_URL} </Text>
        <Button
          title="set user token"
          onPress={() => {
            // userStorage.set('token', '123456');
            setToken('6789');
          }}
        />

        <Text>token: {token || '-'}</Text>
      </View>
    </SafeAreaView>
  );
};

const styles = ScaledSheet.create({
  container: {
    backgroundColor: 'red',
  },
  content: {
    backgroundColor: '#fff',
    fontSize: '20@s',
  },
});

export default HomeScreen;

重启app后,查看效果


Tips

本专栏的代码已开源,后续随着专栏会不断更新https://github.com/ace0109/react-native-template

相关推荐
小码哥_常4 分钟前
安卓黑科技:实现多平台商品详情页一键跳转APP
前端
killerbasd7 分钟前
还是迷茫 5.3
前端·react.js·前端框架
不会敲代码11 小时前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen1 小时前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦1 小时前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen1 小时前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
千寻girling2 小时前
《 Git 详细教程 》
前端·后端·面试
之歆3 小时前
DAY08_CSS浮动与行内块布局实战指南(下)
前端·css
yqcoder3 小时前
CSS Position 全解析:5 种定位模式详解
前端·css
Rhi6374 小时前
从零搭建项目:React 19 + Vite 8 + Tailwind CSS v4 实战配置
前端