Xyl*_*ops 2 nested redux react-redux
嗨,我有两个关于 redux 的问题要问
我如何更新嵌套在对象内部数组中的对象,示例如下
newInStockList:{
newEntry:[
0:{
id:"584f9b926f69ee93d4eb320d",
name:"apple",
amount:"10"
},
1:{
id:"584f9b926f69ee93d4eb31e5",
name:"orange",
amount:"20" <-------- target
},
]
}
Run Code Online (Sandbox Code Playgroud)
我想要更新的目标是那里的橙色数量,因为我已经为它创建了一个减速器,减速器还包括更多的动作
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想将橙色的数量从 20 更新为 30,我在这个减速器中做错了什么?因为我的减速器的输出只会将相同的项目(橙色)再次复制到数组中。我缺少会导致此错误的关键概念是什么?
第二个问题是在reducer的状态下,如果newInStockList里面只有一个item,是否需要newEntry对象?如果没有必要,我该如何删除它以及它如何影响我的代码的其余部分?我尝试删除所有带括号的 newEntry 但它在 action.item 上给出了错误
非常感谢您的帮助:D
在做了更多研究之后,我意识到 如何在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8996 次 |
| 最近记录: |