繁体   English   中英

Redux增加购物车中的数量

[英]Redux increase quantity in a shopping cart

我正在努力使用减速器的功能来添加项目并增加其数量(如果已经存在于购物车中)。 到目前为止,我的代码所做的是将另一个“数量”添加为1,而不是更新状态中已经存在的数量。

这是我的代码:

减速器:

import { ADD_TO_CART } from "../actions/types";

export default function(state = [], action) {
  switch (action.type) {
    case ADD_TO_CART:
      if (state.findIndex(el => el.item.title === action.item.title) === -1) {
       return [...state, { item: action.item, quantity: action.quantity + 1 }];
  } else {
    return [...state, { quantity: action.quantity + 1 }];
  }
default:
  return state;
  }
}

动作:

 import { ADD_TO_CART } from "./types";
 import axios from "axios";

 export const addToCart = id => dispatch => {
   axios
     .get(`https://api.itbook.store/1.0/search/${id}`)
     .then(items =>
       items.map((item, quantity) =>
         dispatch({
           type: ADD_TO_CART,
           item,
           quantity
         })
       )
);
 };

谢谢

您正在找到索引(很好),但没有对索引做任何事情(不是很好):

import { ADD_TO_CART } from "../actions/types";

export default function(state = [], action) {
  switch (action.type) {
    case ADD_TO_CART:
      const index = state.findIndex(el => el.item.title === action.item.title);
      if (index === -1) {
       return [...state, { item: action.item, quantity: action.quantity + 1 }];
      } else {
        // Use map to create a new state object 
        return state.map((item, i) => 
            index === i //Only modify the found index
            ? { ...item, quantity: item.quantity + action.quantity }  //Add the required quantity to the current quantity (not too sure about this)
            : item //Don't modify other items
        );
      }
     default:
       return state;
  }
}
import { ADD_TO_CART } from "../actions/types";

export default function (state = [], action) {
  switch (action.type) {
    case ADD_TO_CART:
      const index = state.findIndex(el => el.item.title === action.item.title);
      if (index > -1) {
        const newState = [...state];
        newState[index] = { ...newState[index], quantity: action.quantity + 1 };
        return newState;
      } else {
        return [...state, { ...action.item, quantity: action.quantity + 1 }];
      }
    default:
      return state;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM