CartReducer.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. export const CartReducer = (state = {}, { type, good = {}, count = 1 }) => {
  2. const { _id } = good
  3. const types = {
  4. CART_ADD() {
  5. count = +count
  6. if (!count) return state
  7. return {
  8. ...state,
  9. [_id]: {
  10. good,
  11. count: count + (state[_id]?.count || 0)
  12. }
  13. }
  14. },
  15. CART_CHANGE() {
  16. count = +count;
  17. if (!count){
  18. return state
  19. }
  20. return {
  21. ...state,
  22. [_id]: {good, count}
  23. }
  24. },
  25. CART_REMOVE() {
  26. let { [_id]: remove, ...newState } = state
  27. return {
  28. ...newState
  29. }
  30. },
  31. CART_CLEAR() {
  32. return {}
  33. },
  34. }
  35. if (type in types) {
  36. return types[type]()
  37. }
  38. return state
  39. }
  40. const actionCartAdd = (good, count=1) => ({type: "CART_ADD", good, count});
  41. const actionCardChange = (good, count) => ({type: 'CART_CHANGE', good, count})
  42. const actionCardRemove = (good) => ({type: 'CART_REMOVE', good})
  43. const actionCardClear = () => ({type: 'CART_CLEAR'})