我正在使用 react native 开发应用程序,我需要删除特定对象,这些对象在过滤方法中给了我,但它给了我一个名为

“只能删除事务中的对象。”

这是我的代码

allObj1 = {
                id : 1,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "11111",
                locationProvider: "2222",
            };

        allObj2 = {
                id : 2,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "22222",
                locationProvider: "2222",
            };

        allObj3 = {
                id : 3,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "333333",
                locationProvider: "2222",
            };

        realm.write(() => {
            realm.create('Location',allObj1 );
            //realm.delete(firstObj);
            realm.create('Location',allObj2 );
            realm.create('Location',allObj3 );
        });

        let locationO = realm.objects('Location');
        //let tanlocation = locationO.filtered('id >1 AND id <3 ');
        // Observe Collection Notifications

        realm.objects('Location').filtered('id >=1 AND id <=3').addListener((tanlocation, changes) => {

            try{
                tanlocation.forEach((realmObj,index) => {
                    realm.delete(realmObj);
                });
            }
            catch(err){
                console.log(err);
            }
        });


        // Unregister all listeners
        realm.removeAllListeners();

        //realm.delete(tanlocation);
        //console.log( tanlocation );

        console.log(locationO);

它向我抛出名为“只能删除事务中的对象”的错误。

有人遇到过这种问题吗?任何人都知道如何修复此或替代方法以实现上述功能

最佳答案

必须将删除包裹在 realm.write 中,就像你对 realm.create 所做的那样。

realm.write(() => {
    realm.delete(realmObj)
})

当我遇到这个问题时,这对我有用。读完这篇才意识到 Github comment

关于react-native - Realm : delete specific object,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41508799/

10-15 15:23