Redux增加购物车中的数量

时间:2018-12-27 16:13:51

标签: javascript reactjs redux

我正在努力使用减速器的功能来添加项目并增加其数量(如果已经存在于购物车中)。 到目前为止,我的代码所做的是将另一个“数量”加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
         })
       )
);
 };

谢谢

2 个答案:

答案 0 :(得分:1)

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

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;
  }
}

答案 1 :(得分:0)

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;
  }
}