cartReducer.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. export function cartReducer(state = {}, { type, good, count = 1 }) {
  2. if (count <= 0) {
  3. type = "CART_DELETE";
  4. }
  5. if (type === "CART_ADD") {
  6. return {
  7. ...state,
  8. [good["_id"]]: {
  9. good,
  10. count: good["_id"] in state ? state[good._id].count + count : count,
  11. },
  12. };
  13. }
  14. if (type === "CART_CHANGE") {
  15. return {
  16. ...state,
  17. [good["_id"]]: {
  18. good,
  19. count: count,
  20. },
  21. };
  22. }
  23. if (type === "CART_DELETE") {
  24. let { [good._id]: toRemove, ...newState } = state;
  25. return newState;
  26. }
  27. if (type === "CART_CLEAR") {
  28. return {};
  29. }
  30. return state;
  31. }
  32. export const actionCartAdd = (good, count = 1) => ({ type: "CART_ADD", good, count: +count });
  33. export const actionCartChange = (good, count = 1) => ({ type: "CART_CHANGE", good, count: +count });
  34. export const actionCartDelete = (good) => ({ type: "CART_DELETE", good });
  35. export const actionCartClear = () => ({ type: "CART_CLEAR" });