Redux更新嵌套状态数组

时间:2016-12-15 05:45:16

标签: nested redux react-redux

嗨,我有两个关于redux的问题,我想问一下

  1. 如何更新在对象内的数组中嵌套的对象,例如:

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

    我想要更新的目标是橙色的数量,我为它创建了一个减速器,减速器还包含更多动作

    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

1 个答案:

答案 0 :(得分:3)

经过一番研究后,我意识到了这一点 How to update single value inside specific array item in redux 通过使用immutability help(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;
        }
    }
相关问题