如何在Redux Reducer中更新2D数组中的值?

时间:2018-09-14 01:42:09

标签: arrays redux

我正在尝试使用redux reducer中的散布运算符更新2D数组中索引(i, j)处的值。 我的减速器看起来像:

export default (state, action) => {
switch(action.type) {
 case INSERT:
   return {
    ...state,
    myArray: [
     ...state.myArray.slice(0, action.i),
     ...state.myArray[action.i] : [
         ...state.myArray[action.i].slice(0, action.j),
         action.newValue,
         ...state.myArray[action.i].slice(action.j),
     ]
     ...state.myArray.slice(action.i),
    ]
  },
};

我的数组如下:

let my Array = [ [1,2,5],[5,8,9],[2,6,9]]

如何使用redux不可变更新模式更新索引(i, j)处的新值?

1 个答案:

答案 0 :(得分:0)

您可以使用两个嵌套的.map调用来更新路径ij处的值

return {
    ...state,
    myArray: state.myArray.map((innerArray, index) => {
        if (index === action.i) return innerArray.map((item, index) => {
            if (index === action.j) return action.newValue
            return item
        })
        return innerArray
    })
}

这比使用散布运算符简单得多,因为您需要更改的值是动态索引。另外,它是不可变的,这是redux的方式