首页 > 解决方案 > Realm.objects() 在 React Native 上返回空对象

问题描述

我正在 React Native 上测试 Realm 数据库(在 Android 上测试),我在检索数据时遇到了一些问题。

我用这个函数来持久化User

insertData = async (data) => {
        await Realm.open({schema: [UserSchema]})
            .then( realm => {
                realm.write(()=>{
                    realm.create('User', {id: '1325487', nickname: "Jack", age: 21});
                })

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

    }

我正在尝试使用这个来检索数据:

findAll = () => {
        Realm.open({schema: [UserSchema]})
            .then( realm => {
                let users = realm.objects('User')
                console.log(users)

            }).catch(error => {
                console.log(error);
            })
    }

这就是我得到的,一个空对象数组:

{"0": {}, "1": {}, "10": {}, "11": {}, "12": {}, "13": {}, 
"14": {}, "15": {}, "16": {}, "17": {}, "18": {}, "19": {}, "2": 
{}, "20": {}, "21": {}, "22": {}, "23": {}, "24": {}, "25": {}, "26": {}, "27": {}, "28": {}, "29": {}, "3": {}, "30": {}, "31": {}, "32": {}, "33": {}, "34": {}, "35": {}, "36": {}, "37": {}, "38": {}, "39": {}, "4": {}, "5": {}, "6": {}, "7": {}, "8": {}, "9": {}}

这是用户架构:

const UserSchema = {
    name: 'User',
    properties: {
        id:         'string',
        nickname:   'string',
        age:        'int'
    }
}

我认为数据正在被持久化,因为当我保存不同的用户并使用过滤器时,结果的数量会有所不同。你知道为什么只有空的物体来吗?或者以某种方式查看我的领域数据库中的内容?

标签: javascriptreact-nativerealm

解决方案


我也面临着同样的问题,即在 react native 从领域数据库中检索数据时的空对象数组。

我发现在 Android Studio logcat 中数据是不可见的,它看起来像:

{"0": {}, "1": {}, "10": {}, "11": {}, "12": {}, "13": {}, "14": {}, "15": {}, "16": {}, "17": {}, "18": {}, "19": {}, "2": {}, "20": {}, "21": {}, "22": {}, "23": {}, "24": {}, "25": {}, "26": {}, "27": {},

但是,您在 Visual Studio(即终端)中检查 logcat,您可以看到结果。

结论:响应中有数据,在 Android Studio logcat 中看不到,但在 Visual Studio 终端中看不到。


推荐阅读