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

相关推荐
p***s91几秒前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
Hello.Reader3 分钟前
PyFlink DataStream Operators 算子分类、函数写法、类型系统、链路优化(Chaining)与工程化踩坑
前端·python·算法
C_心欲无痕6 分钟前
网络相关 - Ngrok内网穿透使用
运维·前端·网络
咖啡の猫7 分钟前
TypeScript-Babel
前端·javascript·typescript
Mintopia32 分钟前
意图OS是未来软件形态,它到底解决了什么问题?
人工智能·react native·前端工程化
Mintopia33 分钟前
🤖 AI 决策 + 意图OS:未来软件形态的灵魂共舞
前端·人工智能·react native
攀登的牵牛花34 分钟前
前端向架构突围系列 - 框架设计(四):依赖倒置原则(DIP)
前端·架构
程序员爱钓鱼41 分钟前
Node.js 编程实战:测试与调试 —— 日志与监控方案
前端·后端·node.js
Mapmost1 小时前
数字孪生项目效率翻倍!AI技术实测与场景验证实录
前端