gpt4 book ai didi

nested - Redux 更新嵌套状态数组

转载 作者:行者123 更新时间:2023-12-02 17:23:06 25 4
gpt4 key购买 nike

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

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

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

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

    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 中做错了什么?因为我的 reducer 的输出只会将相同的项目(橙色)再次复制到数组中。我遗漏了会导致此错误的关键概念是什么?

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

非常感谢您的帮助:D

最佳答案

在做了更多研究之后我意识到 How to update single value inside specific array item in redux通过使用不变性帮助(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;
}
}

关于nested - Redux 更新嵌套状态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com