npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@react-native-ohos/react-native-mmkv-storage

v1.0.0

Published

This library aims to provide a fast & reliable solution for you data storage needs in react-native apps. It uses [MMKV](https://github.com/Tencent/MMKV) by Tencent under the hood on Android and iOS both that is used by their WeChat app(more than 1 Billion

Readme

文档模板:v0.4.2

本项目基于 react-native-mmkv-storage 开发。

该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-mmkv-storage 版本所属关系如下:

| 三方库名称 | 三方库版本(npm地址) | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | 源码地址 | | ------------ | ------------ | ------------------------------ | ------------- | ------------- |------------------------ | ------------- | ------------- | | @react-native-ohos/react-native-mmkv-storage | ~ 1.0.0 | Gitcode Releases | 0.82./0.84 | 是 | API12+ | 12.0.1 | br_rnoh0.82 | | @react-native-ohos/react-native-mmkv-storage | ~ 0.11.3 | Gitcode Releases | 0.77. | 否 | API12+ | 0.11.2 | br_rnoh0.77 | | @react-native-ohos/react-native-mmkv-storage | ~ 0.10.5 | Gitcode Releases | 0.72.* | 是 | API12+ | 0.10.3 | br_rnoh0.72 | | @react-native-oh-tpl/react-native-mmkv-storage | <= 0.10.4@deprecated | Github Releases(deprecated) | 0.72.* | 否 | API12+ | 0.10.3 | sig |

简介

React Native 高性能键值对存储模块。 基于腾讯 MMKV 库在 HarmonyOS 上实现高效键值存储能力,支持字符串、数字、布尔值、对象、数组等多种数据类型存储,支持加密存储、多进程模式以及 React Hooks 等特性。

下载安装

进入到工程目录并输入以下命令:

npm

npm install @react-native-ohos/react-native-mmkv-storage

yarn

yarn add @react-native-ohos/react-native-mmkv-storage

Link

| | 是否支持autolink | RN框架版本 | |--------------------------------------|-----------------|------------| | ~ 1.0.0 | Yes | 0.82/0.84 |

使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md

如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。

首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony

1. Overrides RN SDK

为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。

关于该字段的作用请阅读官方说明

{
  "overrides": {
    "@rnoh/react-native-openharmony": "^0.82.18" // ohpm 在线版本
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
    // "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
  }
}

2. 引入原生端代码

目前有两种方法:

  • 通过 har 包引入;
  • 直接链接源码。

方法一:通过 har 包引入(推荐)

[!TIP] har 包位于三方库安装路径的 harmony 文件夹下。

打开 entry/oh-package.json5,添加以下依赖

"dependencies": {
    "@react-native-ohos/react-native-mmkv-storage": "file:../../node_modules/@react-native-ohos/react-native-mmkv-storage/harmony/mmkv_storage.har"
  }

点击右上角的 sync 按钮

或者在命令行终端执行:

cd entry
ohpm install

方法二:直接链接源码

[!TIP] 如需使用直接链接源码,请参考直接链接源码说明

3. 配置 CMakeLists 和引入 RNOHMMKVStoragePackage

打开 entry/src/main/cpp/CMakeLists.txt,添加:

project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_SKIP_BUILD_RPATH TRUE)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)

add_subdirectory("${RNOH_CPP_DIR}" ./rn)

# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-mmkv-storage/src/main/cpp" ./mmkv_storage)
# RNOH_END: manual_package_linking_1

file(GLOB GENERATED_CPP_FILES "./generated/*.cpp")

add_library(rnoh_app SHARED
    ${GENERATED_CPP_FILES}
    "./PackageProvider.cpp"
    "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)

# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_mmkv_storage)
# RNOH_END: manual_package_linking_2

打开 entry/src/main/cpp/PackageProvider.cpp,添加:

#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "RNOHMMKVStoragePackage.h"

using namespace rnoh;

std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
    return {
      std::make_shared<SamplePackage>(ctx),
+     std::make_shared<RNOHMMKVStoragePackage>(ctx)
    };
}

4. 在 ArkTs 侧引入 RNMMKVStoragePackage

打开 entry/src/main/ets/RNPackagesFactory.ts,添加:

  ...
+ import { RNMMKVStoragePackage } from '@react-native-ohos/react-native-mmkv-storage';

export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
  return [
+    new RNMMKVStoragePackage(ctx)
  ];
}

5. 运行

点击右上角的 sync 按钮

或者在命令行终端执行:

cd entry
ohpm install

然后编译、运行即可。

约束与限制

兼容性

本文档内容基于以下版本验证通过:

  1. RNOH: 0.82.7; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112 SP12;
  2. RNOH: 0.84.1; SDK: HarmonyOS 6.0.2 Release SDK; IDE: 6.0.2 Release; ROM:7.0.0.100 SP9;

权限要求

  • 该库需要申请持久化存储权限

    entry/src/main/module.json5中添加

requestPermissions: [
  {
    name: "ohos.permission.STORE_PERSISTENT_DATA",
  },
],

编译运行API要求

[!TIP] 当前三方库所有版本均已实现版本隔离,支持在 API12+ 工程编译,及 API12+ ROM运行。

HarmonyOS 适配差异

  1. 加密密钥存储:OpenHarmony 平台上的 setSecureKey 不支持 accessibleMode 参数(这是 iOS Keychain 特有的概念)。OpenHarmony 版本使用 Asset Store Kit 替代 iOS Keychain。encryptWithCustomKey(key, secureKeyStorage?, alias?) 的参数顺序为 keysecureKeyStoragealias,后两个参数均为可选;accessibleMode 仅对 iOS Keychain 生效,OpenHarmony 平台上无效。

  2. iOS 专属方法:以下方法在 OpenHarmony 平台上无效:

    • withServiceName(对应 iOS 的 setMMKVServiceName
    • setAccessibleIOS

使用示例

下面的代码展示了这个库的基本使用场景:

[!WARNING] 使用时 import 的库名不变。

import React, { useCallback } from 'react';
import {
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { MMKVLoader, create } from 'react-native-mmkv-storage';

const storage = new MMKVLoader().withEncryption().initialize();
const storage2 = new MMKVLoader().withInstanceID('storage2').initialize();

const useStorage = create(storage);
const useStorage2 = create(storage2);

const App = () => {
  const [user, setUser] = useStorage('user', 'robert');
  const [age, setAge] = useStorage2('age', 24);

  const getUser = useCallback(() => {
    let users = ['andrew', 'robert', 'jack', 'alison'];
    let _user =
      users[
        users.indexOf(user) === users.length - 1 ? 0 : users.indexOf(user) + 1
      ];
    return _user;
  }, [user]);

  const buttons = [
    {
      title: 'setString',
      onPress: () => {
        storage.setString('user', getUser());
      },
    },
    {
      title: 'setMulti',
      onPress: () => {
        const user = getUser();
        console.log('setting user to', user);
        storage.setMultipleItemsAsync([['user', user]], 'string');
      },
    },
    {
      title: 'getMulti',
      onPress: async () => {
        console.log(await storage.getMultipleItemsAsync(['user'], 'string'));
      },
    },
    {
      title: 'setUser',
      onPress: () => {
        setUser(getUser());
      },
    },
    {
      title: 'setAge',
      onPress: () => {
        setAge((age) => age + 1);
      },
    },
    {
      title: 'clearAll',
      onPress: () => {
        storage.clearStore();
      },
    },
    {
      title: 'removeByKeys',
      onPress: async () => {
        const items = await storage.getMultipleItemsAsync(['user'], 'string');
        const keys = items.map(item => item[0]);
        console.log(keys);
        storage.removeItems(keys);
        storage.clearStore();
        console.log(await storage.getMultipleItemsAsync(['user'], 'string'));
      },
    },
  ];

  return (
    <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerText}>
            I am {user} and I am {age} years old.
          </Text>
        </View>
        <ScrollView
          style={{
            width: '100%',
            paddingHorizontal: 12,
          }}>
          {buttons.map(item => (
            <Button
              key={item.title}
              title={item.title}
              onPress={item.onPress}
            />
          ))}
        </ScrollView>
      </SafeAreaView>
    </>
  );
};

const Button = ({ title, onPress }) => {
  return (
    <TouchableOpacity style={styles.button} onPress={onPress}>
      <Text style={{ color: 'white' }}>{title}</Text>
    </TouchableOpacity>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flex: 1,
    backgroundColor: 'white',
  },
  header: {
    width: '100%',
    backgroundColor: '#f7f7f7',
    marginBottom: 20,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 50,
  },
  button: {
    width: '100%',
    height: 50,
    backgroundColor: 'orange',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
    marginBottom: 10,
  },
  headerText: { fontSize: 40, textAlign: 'center', color: 'black' },
});

使用说明

创建存储实例

import { MMKVLoader } from 'react-native-mmkv-storage';

// 创建默认实例
const storage = new MMKVLoader().initialize();

// 创建带自定义ID的实例
const storage2 = new MMKVLoader().withInstanceID('storage2').initialize();

// 创建加密实例
const encryptedStorage = new MMKVLoader().withEncryption().initialize();

基本存储操作

// 存储字符串
storage.setString('username', 'robert');
const username = storage.getString('username');

// 存储数字
storage.setInt('age', 24);
const age = storage.getInt('age');

// 存储布尔值
storage.setBool('isLoggedIn', true);
const isLoggedIn = storage.getBool('isLoggedIn');

// 存储对象
storage.setMap('user', { name: 'robert', age: 24 });
const user = storage.getMap('user');

// 存储数组
storage.setArray('tags', ['react', 'native', 'mmkv']);
const tags = storage.getArray('tags');

// 删除单个键
storage.removeItem('username');

// 删除多个键
storage.removeItems(['username', 'age']);

// 清空存储
storage.clearStore();

// 清空内存缓存
storage.clearMemoryCache();

加密操作

// 创建加密实例
const encryptedStorage = new MMKVLoader().withEncryption().initialize();

// 使用自定义密钥加密
const customKeyStorage = new MMKVLoader()
  .encryptWithCustomKey('my-secret-key', true, 'my-alias')
  .initialize();

// 加密指定键的数据
encryptedStorage.encrypt('sensitiveData');

// 解密指定键的数据
encryptedStorage.decrypt('sensitiveData');

// 更换加密密钥
encryptedStorage.changeEncryptionKey('new-secret-key');

索引器操作

// 获取字符串索引
const stringIndex = storage.indexer.strings;

// 获取数字索引
const numberIndex = storage.indexer.numbers;

// 获取所有索引键
const keys = storage.indexer.getKeys();

// 检查键是否存在
const hasKey = storage.indexer.hasKey('username');

事件订阅

// 订阅事件
const unsubscribe = storage.EventManager.subscribe('userUpdated', (data) => {
  console.log('User updated:', data);
});

// 发布事件
storage.EventManager.publish('userUpdated', { name: 'robert', age: 25 });

// 取消订阅
storage.EventManager.unsubscribe('userUpdated', unsubscribe);

事务管理

// 注册事务
storage.transactions.register(() => {
  console.log('Transaction registered');
});

// 清除所有事务
storage.transactions.clear();

使用 Hooks

import { MMKVLoader, create, useMMKVStorage } from 'react-native-mmkv-storage';

const storage = new MMKVLoader().initialize();
const useStorage = create(storage);

const App = () => {
  const [user, setUser] = useStorage('user', 'robert');
  const [age, setAge] = useStorage('age', 24);

  return (
    <View>
      <Text>User: {user}</Text>
      <Text>Age: {age}</Text>
    </View>
  );
};

接口说明

[!TIP] "Platform"列表示该属性在原三方库上支持的平台。

[!TIP] "OpenHarmony Support"列为 yes 表示 OpenHarmony平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

MMKVLoader 方法

| 名称 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|---------|-------|------|------|---------------------|------| | withInstanceID | id: string | MMKVLoader | No | All | yes | 指定实例ID | | withEncryption | / | MMKVLoader | No | All | yes | 启用加密 | | encryptWithCustomKey | key: string, secureKeyStorage?: boolean, alias?: string | MMKVLoader | No | All | yes | 使用自定义密钥加密 | | generateKey | / | MMKVLoader | No | All | yes | 重新生成加密密钥 | | withServiceName | serviceName: string | MMKVLoader | No | iOS | no | 设置iOS Keychain服务名 | | setAccessibleIOS | accessible: string | MMKVLoader | No | iOS | no | 设置iOS可访问模式 | | setProcessingMode | mode: number | MMKVLoader | No | All | yes | 设置处理模式(单进程/多进程) | | withPersistedDefaultValues | / | MMKVLoader | No | All | yes | 持久化默认值 | | disableIndexing | / | MMKVLoader | No | All | yes | 禁用索引 | | initialize | / | MMKVInstance | No | All | yes | 初始化并返回实例 |

MMKVInstance API

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | setString | function | key: string, value: string | boolean | undefined | No | All | yes | 存储字符串 | | getString | function | key: string, callback?: Function | string | null | undefined | No | All | yes | 获取字符串 | | setInt | function | key: string, value: number | boolean | undefined | No | All | yes | 存储数字 | | getInt | function | key: string, callback?: Function | number | null | undefined | No | All | yes | 获取数字 | | setBool | function | key: string, value: boolean | boolean | undefined | No | All | yes | 存储布尔值 | | getBool | function | key: string, callback?: Function | boolean | null | undefined | No | All | yes | 获取布尔值 | | setMap | function | key: string, value: object | boolean | undefined | No | All | yes | 存储对象 | | getMap | function | key: string, callback?: Function | object | null | undefined | No | All | yes | 获取对象 | | setArray | function | key: string, value: array | boolean | undefined | No | All | yes | 存储数组 | | getArray | function | key: string, callback?: Function | array | null | undefined | No | All | yes | 获取数组 | | setStringAsync | function | key: string, value: string | Promise<boolean | null | undefined> | No | All | yes | 异步存储字符串 | | getStringAsync | function | key: string | Promise<string | null | undefined> | No | All | yes | 异步获取字符串 | | setIntAsync | function | key: string, value: number | Promise<boolean | null | undefined> | No | All | yes | 异步存储数字 | | getIntAsync | function | key: string | Promise<number | null | undefined> | No | All | yes | 异步获取数字 | | setBoolAsync | function | key: string, value: boolean | Promise<boolean | null | undefined> | No | All | yes | 异步存储布尔值 | | getBoolAsync | function | key: string | Promise<boolean | null | undefined> | No | All | yes | 异步获取布尔值 | | setMapAsync | function | key: string, value: object | Promise<boolean | null | undefined> | No | All | yes | 异步存储对象 | | getMapAsync | function | key: string | Promise<object | null | undefined> | No | All | yes | 异步获取对象 | | setArrayAsync | function | key: string, value: array | Promise<boolean | null | undefined> | No | All | yes | 异步存储数组 | | getArrayAsync | function | key: string | Promise<array | null | undefined> | No | All | yes | 异步获取数组 | | setMultipleItemsAsync | function | items: [string, any][], type: DataType | 'map' | Promise | No | All | yes | 异步批量存储 | | getMultipleItemsAsync | function | keys: string[], type: DataType | 'map' | Promise<[key, value][]> | No | All | yes | 异步批量获取 | | getMultipleItems | function | keys: string[], type: DataType | 'map' | [key, value][] | No | All | yes | 批量获取 | | removeItem | function | key: string | boolean | undefined | No | All | yes | 删除单个键 | | removeItems | function | keys: string[] | boolean | undefined | No | All | yes | 删除多个键 | | clearStore | function | / | boolean | undefined | No | All | yes | 清空存储 | | clearMemoryCache | function | / | boolean | undefined | No | All | yes | 清空内存缓存 | | getKey | function | / | { alias: string, key: string } | No | All | yes | 获取加密密钥信息 | | getCurrentMMKVInstanceIDs | function | / | { [id]: boolean } | No | All | yes | 获取当前实例ID列表 | | getAllMMKVInstanceIDs | function | / | array | No | All | yes | 获取所有实例ID列表 | | setItem | function | key: string, value: string, callback?: Function | Promise<boolean | undefined> | No | All | yes | redux-persist兼容方法 | | getItem | function | key: string, callback?: Function | Promise<string | null | undefined> | No | All | yes | redux-persist兼容方法 |

Hooks

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | useMMKVStorage | function | key: string, storage: MMKVInstance, defaultValue?: any, equalityFn?: (prev, next) => boolean | [value: any, setValue: Function] | No | All | yes | 持久化状态Hook;返回值 setValue 支持直接传值或函数式更新 (prev => next);equalityFn 为第 4 参,比较新旧值判断是否刷新状态 | | create | function | storage: MMKVInstance | function | No | All | yes | 创建绑定实例的Hook | | useIndex | function | keys: string[], type: DataType, storage: MMKVInstance | [values: any[], update: Function, remove: Function] | No | All | yes | 索引监听Hook | | useMMKVRef | function | key: string, storage: MMKVInstance, defaultValue: any | { current: any, reset: Function } | No | All | yes | 持久化Ref Hook | | createMMKVRefHookForStorage | function | storage: MMKVInstance | function | No | All | yes | 创建持久化Ref Hook工厂 |

其他函数

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | init | function | / | boolean | No | All | yes | 初始化 MMKV 存储模块 | | isLoaded | function | / | boolean | No | All | yes | 检查模块是否已加载 | | getCurrentMMKVInstanceIDs | function | / | object | No | All | yes | 获取当前已加载实例 ID 列表(独立导出) | | getAllMMKVInstanceIDs | function | / | array | No | All | yes | 获取所有实例 ID 列表(独立导出) |

常量

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | MMKVStoragedeprecated | object | / | object | No | All | yes | 默认导出对象(旧版 API,含 Loader、API、MODES、ACCESSIBLE、getAllMMKVInstanceIDs、getCurrentMMKVInstanceIDs、IDSTORE_ID) | | ProcessingModes | object | / | { SINGLE_PROCESS: 1, MULTI_PROCESS: 2 } | No | All | yes | 处理模式常量,用于 setProcessingMode | | IOSAccessibleStates | object | / | object | No | iOS | no | iOS Keychain 可访问模式常量,用于 setAccessibleIOS(OpenHarmony 平台无效) | | IDSTORE_ID | string | / | string | No | All | yes | 存储实例信息所用的 MMKV ID |

子对象 API

encryption

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | encrypt | function | key?: string, secureKeyStorage?: boolean, alias?: string, accessibleMode?: string | boolean | No | All | yes | 加密指定实例 | | decrypt | function | / | boolean | No | All | yes | 解密指定实例 | | changeEncryptionKey | function | key: string, secureKeyStorage?: boolean, alias?: string, accessibleMode?: string | boolean | No | All | yes | 更换加密密钥 |

indexer

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | strings | property | / | stringsIndex | No | All | yes | 字符串索引 | | numbers | property | / | numbersIndex | No | All | yes | 数字索引 | | booleans | property | / | boolIndex | No | All | yes | 布尔值索引 | | maps | property | / | mapsIndex | No | All | yes | 对象索引 | | arrays | property | / | arrayIndex | No | All | yes | 数组索引 | | getKeys | function | / | Promise<key[]> | No | All | yes | 获取所有索引键 | | hasKey | function | key: string | boolean | No | All | yes | 检查键是否存在 | | strings.getAll | function | / | Promise<[key, value][]> | No | All | yes | 获取所有字符串键值对 | | numbers.getAll | function | / | Promise<[key, value][]> | No | All | yes | 获取所有数字键值对 | | booleans.getAll | function | / | Promise<[key, value][]> | No | All | yes | 获取所有布尔值键值对 | | maps.getAll | function | / | Promise<[key, value][]> | No | All | yes | 获取所有对象键值对 | | arrays.getAll | function | / | Promise<[key, value][]> | No | All | yes | 获取所有数组键值对 |

ev (EventManager)

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | subscribe | function | name: string, handler: Function | void | No | All | yes | 订阅指定事件 | | unsubscribe | function | name: string, handler: Function | void | No | All | yes | 取消订阅指定事件 | | publish | function | name: string, ...args: any[] | void | No | All | yes | 发布事件 | | subscribeMulti | function | names: string[], handler: Function | void | No | All | yes | 批量订阅多个事件 | | unsubscribeAll | function | / | void | No | All | yes | 取消订阅所有事件 | | publishWithResult | function | name: string, ...args: any[] | Promise | No | All | yes | 发布事件并等待处理结果 |

transactions

| 名称 | 类型 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 描述 | |------|------|---------|-------|------|------|---------------------|------| | register | function | type: DataType, transaction: TransactionType, mutator: MutatorFunction | function | No | All | yes | 注册事务 | | unregister | function | type: DataType, transaction: TransactionType | void | No | All | yes | 注销事务 | | clear | function | / | void | No | All | yes | 清除所有事务 |

类型定义

| 类型 | 取值 | 参数类型 | 返回值 | 必填 | 平台 | OpenHarmony平台支持 | 说明 | |------|------|---------|-------|------|------|---------------------|------| | DataType | 'string' | 'number' | 'object' | 'array' | 'boolean' | / | / | No | All | yes | 数据类型。用于 setMultipleItemsAsync / getMultipleItemsAsync / getMultipleItems 的 type 参数、transactions.register / unregister 的 type 参数、以及 useIndex 的第二参数;批量读写 type 参数额外接受 'map'(写入时 'object' 归一为 'map',读取时 'map' 归一为 'object') | | TransactionType | 'beforewrite' | 'onwrite' | 'onread' | 'ondelete' | / | / | No | All | yes | 事务类型:beforewrite=写入前变换值;onwrite=写入后回调;onread=读取时变换返回值(可用于脱敏/包装);ondelete=删除时回调 | | MutatorFunction | (key: string, value?: unknown) => any | key: string, value?: unknown | any | No | All | yes | 事务 mutator 函数签名,即 transactions.register 的第三个参数;返回的值会替换原值(返回 undefined/null 时保留原值) |

遗留问题

其他

目录结构

/rntpc_react-native-mmkv-storage  # 项目根目录
├── harmony                       # 适配代码
│    └─ mmkv_storage.har          # har包
│    └─ mmkv_storage              # 适配核心代码
│          └─ index.ets            # 适配代码入口
│          └─ src/main/ets
│              └─ RNMMKVStorageTurboModule.ets  # TurboModule 实现
│              └─ RNMMKVStoragePackage.ets      # Package 注册
│              └─ AssetStore.ets                # 安全密钥存储
│              └─ Logger.ets                      # 日志工具
│          └─ src/main/cpp
│              └─ MMKVNativeTurboModule.cpp     # C++ TurboModule
│              └─ RNOHMMKVStoragePackage.h           # Package 头文件
│              └─ napi_init.cpp                 # NAPI 初始化
├── index.ts                     # JS入口文件
├── src
│    └─ mmkvinstance.ts          # MMKVInstance 实现
│    └─ mmkvloader.ts            # MMKVLoader 实现
│    └─ encryption.ts            # 加密管理
│    └─ transactions.ts          # 事务管理
│    └─ hooks                    # React Hooks
│    └─ types                    # 类型定义
├── example                       # 示例工程
├── README.md                     # 中文安装使用方法
├── README_en.md                  # 英文安装使用方法

贡献代码

使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR

开源协议

本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。