【问题标题】:Redux - modifying state of a nested array of objectsRedux - 修改嵌套对象数组的状态
【发布时间】:2021-05-23 13:45:32
【问题描述】:

所以我的 Redux 状态应该看起来像这样的结构(当然,columns 数组中没有任何内容,但我认为这样会更容易理解)

columns: [
{id:1, title:'Column Title', items:['A1', 'B1', 'C1', 'D1' ]},
{id:2, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:3, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:4, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:5, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},
{id:6, title:'More Column Title',  items:['A1', 'B1', 'C1',  ]},]

我想要做的是在 items 数组中添加或修改元素,但对于特定列,而不是一次全部,我尝试通过 id 映射和标识列,但我没有做正确的事情,结果在很多错误中。 这是我最后一次尝试,所以控制台日志看起来不错,但我不知道如何以同样的方式修改状态。

case "ADD_ROWS":
  Object.assign({}, state, { 
    columns: [
        ...state.columns, 
        state.columns.map(col => { 
            if (col.id === action.payload.id) { 
                const items = col.items; 
                const newArray = col.items.concat(Array(10).fill())
                console.log(newArray); 
            } 
        }) 
    ] 
}); 

【问题讨论】:

  • 这应该做什么?如您希望如何更新数据的标准是什么?您可以在数据中包含您想要的示例更改吗?您不想扩展 state.columns ,然后还对列进行映射。这会弄乱你的数据结构
  • 可能是这样的? ...state.columns.map( col => { if (col.id === action.payload.id) { ..., return newArray } return col })
  • 我想在列中添加更多“行”,因此向项目添加更多元素,项目被映射如果这种方法会严重混淆我的代码,还有什么替代方法?跨度>

标签: javascript reactjs redux react-redux state


【解决方案1】:

我不完全清楚使用深度嵌套的数据结构是否对可维护性有多大好处。 但是我设法使用immutability-helper

解决了我的问题

所以对于我的特殊情况,解决方案如下所示:

 case "ADD_ROWS":
  return update(state, {
    columns: columns =>
      update(columns || [], {
        [action.payload.id-1]: columnOne =>
          update(columnOne || {}, {
            items: items => update(items || [], { $push: Array(10).fill() })
          })
      })
  });

希望这对正在经历与我类似的不变性地狱的人有所帮助。

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2020-12-08
    • 2017-04-30
    • 2021-10-27
    • 2018-01-21
    • 1970-01-01
    • 2019-04-28
    • 2020-11-17
    • 2019-04-14
    相关资源
    最近更新 更多