首页 > 解决方案 > Realm 在创建对象时崩溃(React Native)

问题描述

这是我的 RealmService 文件:

import Realm from 'realm';

const AuthSchema = {
    name: 'Auth',
    primaryKey: 'id',
    properties: {
        id: {
            type: 'int',
            indexed: true
        },
        time: 'date',
        username: 'string',
        action: 'string'
    }
}

const WiretransferSchema = {
    name: 'Wiretransfer',
    primaryKey: 'id',
    properties: {
        id: {
            type: 'int',
            indexed: true
        },
        time: 'date',
        source: 'string',
        target: 'string',
        amount: 'float',
        comments: {
            type: 'string',
            optional: true
        }
    }
}

let RealmService = {
    findAllAuth: function() {
        return repository.objects('Auth');
    },

    SaveAuth: function(username, action) {
        Realm.open({
            path: 'testtt.realm',
            schema: [AuthSchema, WiretransferSchema]
        }).then(realm => {

            // Get max ID
            var maxId = realm.objects('Auth').max('id');

            realm.write(() => {
                realm.create('Auth', {
                    id: maxId + 1,
                    time: Date.now(),
                    username: username,
                    action: action
                }, true);
            });

            realm.close();  
        }).catch(err => {
            console.log(err);
        });
    }
}

module.exports = RealmService;

调用此代码时,应用程序崩溃且没有任何错误:

realm.write(() => {
                realm.create('Auth', {
                    id: maxId + 1,
                    time: Date.now(),
                    username: username,
                    action: action
                }, true);
            });

只是 write 方法不会使应用程序崩溃。这是创建方法。

如果我禁用 React Native 中的调试工具,应用程序不会崩溃,但领域文件中没有添加任何内容。

我试过 RN 0.57.1​​ 和 0.57.8。重新安装领域,仍然没有运气。问题可能是什么?

标签: androidreact-nativerealm

解决方案


确保您传递的数据类型和对象是相同的。当我的数据类型为int并给它string时,我遇到了同样的崩溃。

在您的情况下,传递new Date()将起作用。

它不会给出任何错误,但应用程序会在 android 和 iOS 上崩溃。也许 Realm 团队会在未来的版本中解决它,因为这个错误已经存在于 Github 论坛中。


推荐阅读