gpt4 book ai didi

react-native - React Native Realm 迁移

转载 作者:行者123 更新时间:2023-12-02 20:49:18 30 4
gpt4 key购买 nike

在 React Native 中,您应该将迁移代码或删除 Realm 数据库的代码(忽略迁移)放在哪里,并且只运行一次?

每次返回登录屏幕时,我都尝试删除 Realm 数据库。当我尝试登录时,它应该将用户信息保存到 Realm 中,然后应用程序正常进行。然而事实并非如此,似乎因为Realm数据库被删除了,所以它没有地方可以保存它。我本以为一旦我登录,通过将用户信息保存到 Realm 中,它会初始化 Realm,然后将用户保存在 Realm 中。

在 Debug模式下,似乎即使删除了 Realm 数据库,一切都正常。 Debug模式要慢很多,那么是否存在某个时间问题?

有没有初始化Realm的方法?

最佳答案

这就是我为使迁移正常工作所做的事情。

我有 realm.js 位于 /src 中,我保存所有的 react 文件。当我需要使用我的 Realm 时,我从'path/to/realm.js'导入 Realm ;realm.js 中,我有旧架构和新架构。

import Realm from 'realm';

const schema = {
name: 'mySchema',
properties: {
name: 'string',
}
};

const schemaV1 = {
name: 'mySchema',
properties: {
name: 'string',
otherName: 'string',
}
};

请注意,它们具有相同的名称。然后在我的realm.js底部,我曾经export default new Realm({schema: [schema]});

我现在有这个:

export default new Realm({
schema: [schemaV1],
schemaVersion: 1,
migration: (oldRealm, newRealm) => {
// only apply this change if upgrading to schemaVersion 1
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('schema');
const newObjects = newRealm.objects('schema');

// loop through all objects and set the name property in the new schema
for (let i = 0; i < oldObjects.length; i++) {
newObjects[i].otherName = 'otherName';
}
}
},
});

如果您不需要迁移数据,您只需使用新架构版本和新架构打开 Realm,它也应该可以工作。

关于react-native - React Native Realm 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42868522/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com