在immutable.js中更改列表中的一项

Changing one item in a list In immutable.js

本文关键字:一项 列表 immutable js      更新时间:2023-10-31

我使用的是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判断放在哪里?

谢谢!

NB:正如另一个答案所提到的,还有一种未记录的indexOf方法,在某些情况下可能更容易使用,只将要查找的值作为参数。

使用findIndex查找需要更改的值的索引,使用set查找要更改的索引:

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);

这很容易。

list = Immutable.List.of(1, 2, 3, 4);
list = list.set(list.indexOf(2), 5);
console.log(list.get(1));  //5

一个更干净的版本,基于forEach。这是一个副作用(变异一个不可变的列表),因此语法类似于使用可变列表-

var list = Immutable.List.of(1, 2, 3, 4);
// Notice no LHS assignment is required as 
// forEach is a side-effect method.
list.forEach((value, index, theList) => {
    // You can check either value, or index
    if (index === soAndSo
        || value.something === something){
        // Just change the value!
        value.prop = someNewValue;
        // Or, in the above case where value
        // is not a reference
        theList.set(index) = newValue;
        // As we found and changed the value
        // of interest, lets exit forEach
        return false;
    }
});

是的,Map也有一个版本。