reactjs - 如何在状态下发送新数量?
问题描述
我有这个代码
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
}
}
推荐阅读
- python - Django 身份验证 LDAP
- python - 用于 Python 的 SGE 数组作业从循环中获取输入
- java - 用 Java 替换 AVI 中的帧
- android - 在 Unity 3d 中从图库中选择图像和视频
- r - How to remove multiple columns from a dataframe with column list
- python - TensorFlow Ai 没有进展,gym breakout-ram-v4
- openmdao - 从记录器停止的位置和迭代次数重新开始
- r - 从某个时间范围内的最高先前值中减去一个值,以 r 为单位
- python - 根据数据框之间的距离和 id 创建数据框
- hyperledger-fabric - Hyperledger Fabric 中事件的用途和用例是什么?