【问题标题】:how to add quantity with product item in Reducer ADD_TO_CART using React Redux如何使用 React Redux 在 Reducer ADD_TO_CART 中添加产品项目的数量
【发布时间】:2018-11-27 06:08:06
【问题描述】:
CartReducer.js



export default function cartReducer(state = {cart: [],qty:1 }, action) {
  switch (action.type) {
     case ADD_TO_CART:
         if (state.cart.indexOf(action.product) !== -1) {
              return state   // i want add quantity with increment (qty++)
          }
          return { cart:[...state.cart, action.product] } // send qty with cart
      case REMOVE_FROM_CART:
          return {
               cart: state.cart.filter(id => id !== action.product_id)
             }
       default:
     }
  retrun state;
}

我想通过产品项目传递数量,如果多次单击同一项目 (AddToCart) 然后增加数量 (qty++)

请帮帮我...

【问题讨论】:

    标签: reactjs redux shopping-cart reducers


    【解决方案1】:

    首先,一个操作应该始终有一个type 和一个payload,其中有效负载是一个包含您的数据的对象,在本例中是产品。

    其次,数量应该是您cart 数组中每个产品的一部分,这样您就可以跟踪每个产品。

    然后,我会做以下事情:

    const { type, payload } = action // extract the type and payload before the switch statement
    
    case ADD_TO_CART: {
      const productId = payload.product.id
    
      if (state.cart.findIndex(product => product.id === productId) !== -1) {
        const cart = state.cart.reduce((cartAcc, product) => {
          if (product.id === productId) {
            cartAcc.push({ ...product, qty: product.qty++ }) // Increment qty
          } else {
            cartAcc.push(product)
          }
    
          return cartAcc
        }, [])
    
        return { ...state, cart }
      }
    
      return { ...state, cart: [...state.cart, { ...payload.product, qty: 0 }] }
    }

    【讨论】:

    • Not Working, Uncaught TypeError: 20 is not a function at Array.findIndex ()
    • 是的,我更新了我的答案,我很快写了这个脚本并没有测试它...... findIndex 必须有一个比较函数,它只有值,现在它应该可以工作,但是请想想这段代码的作用,而不仅仅是复制/粘贴它。
    • 欢呼......它正在工作,非常感谢,我正是想要这个。但是 qty++ 不工作我改成 qty+1 再次谢谢你
    猜你喜欢
    • 2022-01-05
    • 2021-05-26
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2021-04-26
    • 2017-10-24
    • 1970-01-01
    相关资源
    最近更新 更多