redux购物车减少物品数量

时间:2018-03-27 06:08:41

标签: reactjs redux

我想用reduct选项实现redux购物车程序。 cart.js页面

const addedIds = (state = initialState.addedIds, action) => {
  switch (action.type) {
    case ADD_TO_CART:
      if (state.indexOf(action.productId) !== -1) {
        return state
      }
      return [ ...state, action.productId ]

      case REDUCT_FROM_CART:
       return state.filter(productId => action.productId !== productId)
    default:
      return state
  }
}

const quantityById = (state = initialState.quantityById, action) => {

  switch (action.type) {
    case ADD_TO_CART:
      const{ productId } = action
      return { ...state,
        [productId]: (state[productId] || 0) + 1
      }

      case REDUCT_FROM_CART:

      return { ...state,
        [productId]: state[productId] - 1
      } 
      default:
      return state
  }
}

&安培;这是ProductItem页面

const ProductItem = ({ product, onAddToCartClicked, onReductFromCartClicked }) => (
  <div style={{ marginBottom: 20 }}>
    <Product
      title={product.title}
      price={product.price}
      quantity={product.inventory} />
    <button
      onClick={onAddToCartClicked}
      disabled={product.inventory > 0 ? '' : 'disabled'}>
      {product.inventory > 0 ? 'Add to cart' : 'Sold Out'}
    </button>
    <button 
    onClick={onReductFromCartClicked}
      disabled={product.inventory < 0 ? 'disabled' :'' }>
      {product.inventory < 0 ? 'No Item' : 'Reduct from cart' }
    </button>

  </div>
)

所有更改是什么让这个程序正常运行还原功能?是否有任何其他代码部分需要更改而不是上面给出的代码?请有人帮我解决这个问题。 谢谢

1 个答案:

答案 0 :(得分:0)

case REMOVE_TO_CART:
        console.log("removed ADD");

      return [ ...state.slice(0,state.indexOf(action.productId),
          ...state.slice(state.indexOf(action.productId)+1))
      ];
    default:
      return state

此代码可能有助于解决您的问题