Redux 更新嵌套状态数组

Redux update nested state array

你好,我有两个关于 redux 的问题想问

  1. 如何更新嵌套在对象内部数组中的对象,示例如下所示

    newInStockList:{
        newEntry:[
            0:{
                id:"584f9b926f69ee93d4eb320d",
                name:"apple",
                amount:"10"
            }, 
            1:{
                id:"584f9b926f69ee93d4eb31e5",
                name:"orange",
                amount:"20"  <-------- target
            }, 
        ]
    }
    

    我想更新的目标是那里的橙色数量,因为我已经为它创建了一个 reducer,这个 reducer 还包括一些更多的动作

    export var newInStockList = (state = {newEntry:[]}, action)=>{
        switch (action.type){
            case 'INSERT_NEW_ITEM_TO_INSTOCK_LIST':
                return {
                    newEntry:[...state.newEntry, action.item]
                };
            case 'REMOVE_ITEM_FROM_INSTOCK_LIST':
                return {
                    newEntry:[
                        ...state.newEntry.slice(0, action.targetItemIndex),
                        ...state.newEntry.slice(action.targetItemIndex + 1)
                    ]
                }
            case 'EDIT_ITEM_FROM_INSTOCK_LIST':
                return {
                    newEntry:[
                        ...state.newEntry,
                        state.newEntry[action.targetItemIndex]:{      <----problem
                            amount:action.amount                      <----problem
                        }                                             <----problem
                    ]
                }
            default:
                return state;
        }
    }
    

    如果我想将橙色的数量从 20 更新为 30,我在这个减速器中做错了什么?因为我的 reducer 的输出只会将相同的项目(橙色)再次复制到数组中。我遗漏的关键概念是什么会导致这个错误?

  2. 第二个问题是在reducer的状态下,如果newInStockList里面只有一个项目,是否需要newEntry对象?如果没有必要,我该如何删除它以及它如何影响我的其余代码?我试图删除所有带括号的 newEntry 但它在 action.item

  3. 上给出错误

非常感谢您的帮助:D

在做了更多研究后我意识到 通过使用不变性帮助 (https://facebook.github.io/react/docs/update.html)

,线程遇到了与我类似的问题

代码更新:

     import update from 'react-addons-update'; 

     export var newInStockList = (state = {newEntry:[]}, action)=>{
        switch (action.type){
            case 'INSERT_NEW_ITEM_TO_INSTOCK_LIST':
                return {
                    newEntry:[...state.newEntry, action.item]
                };
            case 'REMOVE_ITEM_FROM_INSTOCK_LIST':
                return {
                    newEntry:[
                        ...state.newEntry.slice(0, action.targetItemIndex),
                        ...state.newEntry.slice(action.targetItemIndex + 1)
                    ]
                }
            case 'EDIT_ITEM_FROM_INSTOCK_LIST':
                return update(state,{
                    newEntry:{
                        [action.targetItemIndex]:{
                            amount:{$set : action.amount}
                        }
                    }
                })
            default:
                return state;
        }
    }