React Native 领域迁移

fes*_*fes 2 realm react-native realm-migration

在 React Native 中,你应该把迁移代码或删除领域数据库(忽略迁移)的代码放在哪里,让它只运行一次?

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

在调试模式下,似乎即使删除 Realm 数据库,一切正常。调试模式要慢很多,所以某处有时间问题吗?

有没有初始化 Realm 的方法?

Sye*_*fri 5

这就是我为使迁移工作而做的事情。

我已经realm.js找到了/src保存所有 React 文件的位置。当我需要用我的境界我import realm from 'path/to/realm.js';realm.js我有我的旧模式和我的新的模式。

import Realm from 'realm';

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

const schemaV1 = {
    name: 'mySchema',
    properties: {
        name: 'string',
        otherName: 'string',
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,它们具有相同的名称。然后在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';
            }
        }
    },
});
Run Code Online (Sandbox Code Playgroud)

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