我正在使用immutable.js,我的数据结构如下:
class ItemList extends Record({
items: new List()
})
我想编写一个函数来更改此列表中的一项并保持其他项不变。例如,一个{1,2,3,4}的列表,我需要一个函数,如果其中一项等于2,则将其更改为5。
我正在使用类似的东西
updateInfo(updatedInfo) {
return this.withMutations(itemList => {
itemList.set('items', list);
});
}
我的问题是在这个函数中,我怎样才能只更新一项? if判断应该放在哪里?
谢谢!
最佳答案
注意:正如另一个答案提到的,还有未记录的 indexOf
方法,在某些情况下可能更容易使用,仅将要查找的值作为参数。
使用findIndex
查找需要更改的值的索引,并设置
要更改的索引:
list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.findIndex(function(item) {
return item === 2;
}), 5);
ES6:
list = list.set(list.findIndex((item) => item === 2), 5);
如果您需要旧值来更改它,您可以使用update
而不是像这样设置:
list = list.update(list.findIndex(function(item) {
return item === 2;
}), function(oldValue) {
return 5;
});
ES6:
list = list.update(list.findIndex((item) => item === 2), (oldValue) => 5);
关于javascript - 在 immutable.js 中更改列表中的一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366308/