mli*_*956 4 javascript immutable.js redux
我正在使用immutable.js,我的数据结构如下:
class ItemList extends Record({
items: new List()
})
Run Code Online (Sandbox Code Playgroud)
我想编写更改此列表中的一个项目并保持其他相同的功能.例如,{1,2,3,4}的列表,如果项目等于2,我需要一个函数,将其更改为5.
我正在使用类似的东西
updateInfo(updatedInfo) {
return this.withMutations(itemList => {
itemList.set('items', list);
});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在这个函数中,我怎样才能更新一个项目?我应该把if判断放在哪里?
谢谢!
这很容易.
list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.indexOf(2), 5);
console.log(list.get(1)); //5
Run Code Online (Sandbox Code Playgroud)
注意:如另一个答案所述,还有一种未indexOf公开记录的方法,在某些情况下可能更易于使用,仅将要查找的值作为参数即可。
使用findIndex找到你需要的变化和价值的指标set与指数的变化:
list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.findIndex(function(item) {
return item === 2;
}), 5);
Run Code Online (Sandbox Code Playgroud)
ES6:
list = list.set(list.findIndex((item) => item === 2), 5);
Run Code Online (Sandbox Code Playgroud)
如果您需要更改旧值,则可以使用update而不是set来代替:
list = list.update(list.findIndex(function(item) {
return item === 2;
}), function(oldValue) {
return 5;
});
Run Code Online (Sandbox Code Playgroud)
ES6:
list = list.update(list.findIndex((item) => item === 2), (oldValue) => 5);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3420 次 |
| 最近记录: |