rntpc_react-native-mmkv-storage:基于 react-native-mmkv-storage 的 OpenHarmony 适配版,MMKV 高性能键值存储(微信开源)

基于 react-native-mmkv-storage 的 OpenHarmony 适配版,MMKV 高性能键值存储(微信开源)

分支4Tags6
文件最后提交记录最后更新时间
3 年前
3 个月前
9 天前
16 天前
9 天前
9 天前
7 年前
9 天前
2 年前
4 年前
16 天前
1 年前
6 年前
2 个月前
1 个月前
4 天前
4 天前
1 年前
8 个月前
9 天前
8 个月前

文档模板:v0.4.2

react-native-mmkv-storage

本项目基于 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./0.86.* 是 API12+ 12.0.1 master
@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

链接

是否支持 AutoLink RN 框架版本
~ 1.0.0 是 0.82/0.84/0.86

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

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

ManualLink:此步骤为手动配置原生依赖项的指导

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

1. 覆盖 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 包引入(推荐)

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

方法二:直接链接源码

如需使用直接链接源码,请参考[直接链接源码说明](https://gitcode.com/CPF-RN/usage-docs/blob/master/zh-cn/link-source-code.md)

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.ets,添加:

  ...
+ 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;
  3. RNOH: 0.86.1; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 26.0.0 Release; ROM:6.0.0.120;

权限要求

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

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

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

编译运行API要求

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

HarmonyOS 适配差异

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

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

    • withServiceName(对应 iOS 的 setMMKVServiceName)
    • setAccessibleIOS

使用示例

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

使用时 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;

// 获取所有索引键(getKeys 返回 Promise,需要 await 或 .then() 消费)
const keys = await storage.indexer.getKeys();

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

事件订阅

// 订阅事件(subscribe 返回 void,需保存 handler 引用用于取消订阅)
const onUserUpdated = (data) => {
  console.log('User updated:', data);
};
storage.ev.subscribe('userUpdated', onUserUpdated);

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

// 取消订阅(传入与订阅时相同的 handler 引用)
storage.ev.unsubscribe('userUpdated', onUserUpdated);

事务管理

// 注册事务
storage.transactions.register('object', 'onwrite', (key, value) => {
  console.log('Object written:', key, value);
});

// 清除所有事务
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>
  );
};

useIndex / useMMKVRef 示例

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

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

// useIndex:监听某类索引,返回该类型全部值及更新/移除方法
const App = () => {
  const [values, update, remove] = useIndex(['str1', 'str2'], 'string', storage);

  return (
    <View>
      {values.map((v, i) => (
        <Text key={i}>{v}</Text>
      ))}
      <Button title="更新 str1" onPress={() => update('str1', 'newValue')} />
      <Button title="移除 str2" onPress={() => remove('str2')} />
    </View>
  );
};

// useMMKVRef:持久化的 ref,值变更自动写回存储
const RefComponent = () => {
  const ref = useMMKVRef('myRef', storage, { count: 0 });

  return (
    <View>
      <Text>{JSON.stringify(ref.current)}</Text>
      <Button title="递增" onPress={() => { ref.current = { count: ref.current.count + 1 }; }} />
      <Button title="重置" onPress={() => ref.reset()} />
    </View>
  );
};

接口说明

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

"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] 否 全部 是 持久化状态 Hook;返回值 setValue 支持直接传值或函数式更新 (prev => next);equalityFn 为第 4 个参数,用于比较新旧值以判断是否刷新状态
create function storage: MMKVInstance function 否 全部 是 创建绑定实例的 Hook
useIndex function keys: string[], type: DataType, storage: MMKVInstance [values: any[], update: Function, remove: Function] 否 全部 是 索引监听 Hook
useMMKVRef function key: string, storage: MMKVInstance, defaultValue: any { current: any, reset: Function } 否 全部 是 持久化 Ref Hook
createMMKVRefHookForStorage function storage: MMKVInstance function 否 全部 是 创建持久化 Ref Hook 的工厂函数

其他函数

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

常量

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

子对象 API

encryption

名称 类型 参数类型 返回值 必填 平台 OpenHarmony平台支持 描述
encrypt function key?: string, secureKeyStorage?: boolean, alias?: string, accessibleMode?: string boolean No All partial 加密指定实例,accessibleMode 仅对 iOS Keychain 生效,OpenHarmony 平台上无效,详见HarmonyOS 适配差异
decrypt function / boolean No All yes 解密指定实例
changeEncryptionKey function key: string, secureKeyStorage?: boolean, alias?: string, accessibleMode?: string boolean No All partial 更换加密密钥,accessibleMode 仅对 iOS Keychain 生效,OpenHarmony 平台上无效,详见HarmonyOS 适配差异

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) ,请自由地享受和参与开源。

项目介绍

基于 react-native-mmkv-storage 的 OpenHarmony 适配版,MMKV 高性能键值存储(微信开源)

定制我的领域