首页 > 解决方案 > 如何在状态下发送新数量?

问题描述

我有这个代码

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

但新数量不发送状态。这可能是什么原因造成的?

标签: reactjsredux

解决方案


我在这里发现了几个问题。首先,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
  }
}

代码沙盒



推荐阅读