如何发送状态中的新数量



我有这个代码

const initialState = {
asideItems: [],
total: 0
}
const asideReducer = (state = initialState, action) =>{
switch(action.type) {
case ADD_TO_ASIDE:
const item = action.payload
const existItem =  state.asideItems.find(item => action.payload.id === item.id)
if(existItem)
{
console.log(item)
item.quantity += 1
console.log(item)
return{
...state,
total: state.total + item.price,
}
}
else{
return{
...state,
asideItems: [...state.asideItems , item],
total: state.total + item.price
}
}
default:
return state
}
}

我做了简单的验证,如果在asideItems中存在这样的项目,则更改其计数。例如item.quantity += 1工作的真正

console.log(item) // Quantity = 1
item.quantity += 1
console.log(item) // Quantity =  2

但新的数量不会在州内发送。是什么原因造成的?

我在这里发现了几个问题。首先,switch语句在语法上无效。需要引用ADD_TO_ASIDE。其次,你没有使用函数方法来更新你的物品数量,相反,你在原地改变变量,它不会以这种方式使用redux。查看减速器的规则。

const asideReducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_TO_ASIDE":
const updatedAsideItems = state.asideItems.map(currentItem => {
if (currentItem.id === action.payload.id) {
return {...currentItem, quantity: (currentItem.quantity || 0) + 1}
} else {
return currentItem
}
})

return { ...state, asideItems: updatedAsideItems, total: state.total + action.payload.price}
default:
return state
}
}

Codesandbox


最新更新