react native 如何正确使用realm

react native 如何正确使用realm

Realm是一个支持云同步的快速的新型的数据库,是SQLite的替代品。Realm的官网实际上对Realm的使用有相当详细的讲解,但是对于我们实际开发中可能出现的一些问题官方文档可能会有没有提到的地方,这篇博客旨在记录笔者在使用realm时踩到的一些坑

安装

安装过程官方说的很明确,但是要注意我们需要安装两个依赖:

1
2
3
4
# 安装realm库
npm install realm
# 安装一些操作realm的hooks等
npm install @realm/react

在使用过程中也需要注意,我们引入依赖的位置。

使用

目前的realm支持两种写法,一种是直接引入的方法:

1
2
3
4
5
6
7
8
9
10
11
12
import React from 'react';
import {RealmProvider} from '@realm/react';
// Import your models
import {Profile} from '../../../models';

export const AppWrapper = () => {
return (
<RealmProvider schema={[Profile]}>
<RestOfApp />
</RealmProvider>
);
};

在你需要的时候仅需要:

1
2
import {useQuery} from '@realm/react';
const profiles = useQuery(Profile);

如果你有多个schema,或者说多个表,直接在RealmProvider中的schema属性中添加即可,因为这里它接受一个数组嘛。

更好的使用

但是我认为上述方法并不是最好的使用方法,我这里还是推荐直接使用createRealmContext的方式,这样能够让我们更灵活的使用realm config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 配置realm
const config: Realm.Configuration = {
schema: [Settings, DarftSchema],
schemaVersion: 1,
onMigration: (oldRealm, newRealm) => {
newRealm.deleteAll();
},
};


// 创建Provider
const {RealmProvider, useRealm, useObject, useQuery} =
createRealmContext(config);


// 包裹App剩余部分
function App(): React.JSX.Element {
return (
<RealmProvider>
<RealmContext.Provider value={{useRealm, useObject, useQuery}}>
<LayoutWarp />
</RealmContext.Provider>
</RealmProvider>
);
}

但是由于我们使用了这种方式之后,就不能使用直接引用的全局api了,所以我们必须想办法把api传递给后代组件。我的建议是:useContext

1
2
3
4
5
export const RealmContext = createContext({
useRealm,
useObject,
useQuery,
});

在需要使用这些api的子组件调用:

1
2
const {useRealm, useObject} = useContext(RealmContext);
const realm = useRealm();

这样就不会报错了。


react native 如何正确使用realm
2024/01/17/technology/react/rn_use_realm/
作者
charlesix59
发布于
2024年1月17日
许可协议