如果购物车中有产品,如何更新数量

时间:2020-09-08 23:06:05

标签: reactjs

从添加到购物车的情况来看,我在减速器中的逻辑存在问题,如果购物车中存在产品,则其数量应为每次点击增加2个数量,而每次点击应增加1个数量。

module API
  ApplicationName.controllers :health_check do
    get :index do
      status = {
          read_success: read_successful,
          write_success: write_successful,
          exception: check_exception
      }
       [200, {}, [status.to_json]]
    end
  end
end

def read_successful
  begin
    ActiveRecord::Base.connection.execute("SELECT 1")
    true
  rescue
    false
  end
end

def write_successful
  begin
    # logic to check write to database, which table should i write to?
    true
  rescue
    false
  end
end

def check_exception
  begin
    ActiveRecord::Base.connection.execute("SELECT 1")
    nil
  rescue Exception => e
    return e.message
  end
  begin
    # logic to check write to database, which table should i write to?
    nil
  rescue Exception => e
    return e.message
  end
end

2 个答案:

答案 0 :(得分:0)

让newCart = [... state.basket] 让itemInCart = newCart.find((item)=> item.id === action.item.id);

        if (itemInCart) {
            return {
                ...state,
                basket: [{...itemInCart, quantity: itemInCart.quantity++} ]
            }
        } else {
            return {
                ...state,
                basket: [...state.basket, action.item]
            }
        };  

此方法有效,但是如果要插入新产品,请替换购物车中的现有产品

答案 1 :(得分:-1)

我认为let newCart = [...state.basket]正在创建一个新数组,但是正在复制购物车中对象的引用,因此您正在改变状态。试试

let itemInCart = newCart.find((item) => item.id === action.item.id);
let newItem;
  if (itemInCart) {
    newItem = {...itemInCart, quantity: itemInCart.quantity++}
  }else {
    newItem = {
    ...action.item,
    quantity:1
  };
newCart.push(newItem)

即将购物车中的物品复制到新对象并更改数量。