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

标签 javascript redux immutable.js

我正在使用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/

相关文章:

javascript - 在 EXTJS 中的选项卡面板内添加 PORTAL : Using the Portal Demo by EXTJS

javascript - 来自另一个 Controller 的 Ionic 1 调用函数

javascript - 用 div 替换框架

javascript - 组件未呈现

javascript - 在 sagas 中使用 race 的优势

javascript - 无法刺激模态 : React-Redux 中输入的变化

javascript - PUT 请求成功,但 React、Redux 应用程序崩溃

Python 不可变类型 ids 和 is 语句

javascript - 防止二维数组变异,javascript

reactjs - 什么时候在 React 中使用 Immutable.js 有意义?