繁体   English   中英

将对象推入嵌套的 Reducer 数组?

[英]Pushing Object Into Nested Reducer Array?

问题:将新的有效负载对象推送到嵌套的 redux reducers 状态的最佳方法是什么?

我想使用当前状态索引值将新项目位置推送到 reducers 函数中的当前列表数组。

我目前的 REDUX 行动:

 export const addLocation = () => { return (dispatch) => { axios.post("/inventory/lists/addlocation", locationData).then((res) => { dispatch({ type: ADD_POSTED_LOCATION, payload: {location: "test", count: 0, _id: "6a5e4f6ae51g6ea5r1ga6e1rf"}, }); }); }; };

我目前的减速机:

 const initialState = { lists: [], currentIndex: { listIndex: null, itemIndex: null, locationIndex: null }, }; export default function(state = initialState, action) { switch (action.type) { case ADD_POSTED_LOCATION: const listIndex = state.currentIndex.listIndex; const itemIndex = state.currentIndex.listIndex; return { ...state, lists: state.lists[listIndex ].items[itemIndex].locations.push(action.payload) };
我目前的结果很简单

 lists: [a number, excluding the list objects and values]

想要的结果:

 Lists: [ { _id: "L1", items: [{ number: "n1", locations: [{ location: "L1" }, { location: "L2" }] }, { number: "n2", locations: [{ location: "L1" }, { location: "L2" }, { location: "L3" }, { location: "L4" }, { location: "L5" } ] } ] ]

您应该始终浅复制您正在更新的状态的任何部分,包括嵌套数组和对象。

export default function (state = initialState, action) {
  switch (action.type) {
    case ADD_POSTED_LOCATION:
      const listIndex = state.currentIndex.listIndex;
      const itemIndex = state.currentIndex.listIndex;
      return {
        ...state,
        lists: state.lists.map((list, lIndex) =>
          lIndex === listIndex
            ? {
                ...list,
                items: list.items.map((item, iIndex) =>
                  iIndex === itemIndex
                    ? {
                        ...item,
                        locaitons: [...item.locations, action.payload]
                      }
                    : item
                )
              }
            : list
        )
      };
  }
}

修正了一些简单的错误和语法。 这是解决方案,谢谢德鲁!

我了解到您必须使用扩展运算符 (...) 制作嵌套对象结构的浅拷贝 此外,利用可选的.map() 索引参数允许您使用映射数组的索引值与其他索引变量进行比较。 非常好!

 export default function(state = initialState, action) { switch (action.type) { case ADD_POSTED_LOCATION: return { ...state, lists: state.lists.map((list, lIndex) => lIndex === state.currentIndex.listIndex ? { ...list, items: list.items.map((item, iIndex) => iIndex === state.currentIndex.itemIndex ? { ...item, locations: [...item.locations, action.payload] } : item ) } : list ) }; } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM