【问题标题】:Immutable.js update deeply nested MapImmutable.js 更新深度嵌套的 Map
【发布时间】:2018-01-15 13:43:11
【问题描述】:

我在更新 redux 商店时遇到问题。我在商店中有表格数据,更新补丁附带选择和要更新的值。商店的状态是这样的:

const state = fromJS({
  data: {
    rows: {
      row1: {
        col1: { amount: 1 },
        col2: { amount: 1 },
        col3: { amount: 1 },
        col4: { amount: 1 },
      },
      row2: {
        col1: { amount: 2 },
        col2: { amount: 2 },
        col3: { amount: 2 },
        col4: { amount: 2 },
      },
      row3: {
        col1: { amount: 3 },
        col2: { amount: 3 },
        col3: { amount: 3 },
        col4: { amount: 3 },
      },
      row4: {
        col1: { amount: 4 },
        col2: { amount: 4 },
        col3: { amount: 4 },
        col4: { amount: 4 },
      },
    }
  }
});

const newAmount = 5;

const selection = [
  { row: 'row1', column: 'col1' },
  { row: 'row1', column: 'col2' },
  { row: 'row2', column: 'col1' },
  { row: 'row2', column: 'col2' },
];

选择只能是一个单元格,也可以是一行或多行上的多个单元格。每个单元格都应使用相同的值进行更新。更新商店以使下一个状态如下所示的正确方法是什么。

const nextState = fromJS({
  data: {
    rows: {
      row1: {
        col1: { amount: 5 }, // updated with newAmount 
        col2: { amount: 5 }, // updated with newAmount
        col3: { amount: 1 },
        col4: { amount: 1 },
      },
      row2: {
        col1: { amount: 5 }, // updated with newAmount
        col2: { amount: 5 }, // updated with newAmount
        col3: { amount: 2 },
        col4: { amount: 2 },
      },
      row3: {
        col1: { amount: 3 },
        col2: { amount: 3 },
        col3: { amount: 3 },
        col4: { amount: 3 },
      },
      row4: {
        col1: { amount: 4 },
        col2: { amount: 4 },
        col3: { amount: 4 },
        col4: { amount: 4 },
      },
    }
  }
});

【问题讨论】:

  • 我不知道 Immutable.js,但是当你处理对象不变性时,核心对象不会改变,而是给你新对象

标签: javascript redux immutable.js


【解决方案1】:

我能找到的最简单的方法(代码方面)是:

const newState = state.withMutations(newStore => {
  selection.forEach((selection) => {
    newStore.setIn(['data', 'rows', selection.row, selection.column, 'amount'], newAmount)
  }) 
})

这种方法的好处是您只需迭代将要更改的内容。我认为没有withMutation 不值得这样做,因为代码可能看起来很难处理。

【讨论】:

  • 另一种有效的方法是仅通过更改来模拟状态对象并执行 mergeDeep。
  • 这是我最初的方法,但我从未成功过。你的解决方案很棒。谢谢!
猜你喜欢
  • 2015-11-27
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 2018-06-04
  • 2019-07-10
相关资源
最近更新 更多