Mai*_*ria 3 javascript arrays updates realm react-native
我有一个领域组织和票证。一个组织有很多票。因此,要更新组织,它看起来像这样:
try {
realm.write(() => {
realm.create('Organization', {
id: organization.id,
name: organization.name,
ticket: downloadTickets(organization.id)
}
, true)
})
console.log("inserting/updating ogranization")
} catch(err) {
console.warn(err)
}
Run Code Online (Sandbox Code Playgroud)
该downloadTickets函数返回一个对象数组。这将在我最初的写作中起作用。但是如果我想更新数组,我想向数组添加对象但不覆盖整个数组。如何在不获取当前值、将其附加到新值并将其返回到对象的情况下执行此操作?这似乎太慢了。
当您create()与true参数一起使用时,您将覆盖现有对象的属性。您想要的是修改现有数据。
为此,您必须以某种方式引用原始数组。您可以迭代新的Tickets 并将push()它们放入数组中,或者使用concat()现有数组并传入新数组。
try {
realm.write(() => {
var org = realm.create('Organization', {
id: organization.id,
name: organization.name
}
, true)
// Do this
var newTickets = downloadTickets(organization.id);
for(var i = 0; i < newTickets.length; i++) {
org.ticket.push(newTickets[i]);
}
// or this
org.ticket = org.ticket.concat(downloadTickets(organization.id));
})
console.log("inserting/updating ogranization")
} catch(err) {
console.warn(err)
}
Run Code Online (Sandbox Code Playgroud)
附带说明:引用数组不会将整个数组加载到内存中。数组的实际数据仅在磁盘上,直到您显式访问它,Realm 然后从磁盘读取它。访问数组来添加新的Tickets 并不是一个昂贵的操作。
| 归档时间: |
|
| 查看次数: |
4227 次 |
| 最近记录: |