【问题标题】:react native shopping cart with redux用 redux 反应原生购物车
【发布时间】:2020-10-15 14:30:07
【问题描述】:

您好,我刚开始使用 react native 开始 redux,我正在尝试制作一个送餐应用程序。例如,每种食物都有饮料或甜点等选项。我希望如果用户添加一个购物篮和一个项目,我们会检查选择的选项是否相同以增加数量,如果它们不同,我想将另一个具有新选项的项目添加到全局状态。只有我尝试了很多东西,似乎都没有达到我的期望。我传递给全局状态的数据结构就是这种形式。

cartProduct = [
  {
    id: itemId,
    restaurantName: restaurantName,
    name: itemName,
    quantity: quantity,
    price: price
    selectedOption: [
      optionId: optionId,
      itemId: itemId,
      name: itemName,
    ]
  }
]

这是我在减速器中使用添加到购物车操作编写的代码

switch (action.type) {
        case 'ADD_TO_CART':
            const cartProductIndex = state.cartProduct.findIndex(item => item.id === action.value.id)
            if (cartProductIndex == -1) {
                nextState = {
                    ...state,
                    cartProduct: [...state.cartProduct, action.value]
                }
            } else {
                state.cartProduct[cartProductIndex].selectedOption.map(item => {
                    if (item.item === action.value.selectedOption.item) {
                        let newArray = [...state.cartProduct]
                        newArray[cartProductIndex] = {
                            ...newArray[cartProductIndex],
                            quantity: state.cartProduct[cartProductIndex].quantity + 1,
                            totalPrice: state.cartProduct[cartProductIndex].totalPrice + action.value.totalPrice
                        }
                        nextState = {
                            ...state,
                            cartProduct: newArray
                        }
                    } else {
                        nextState = {
                            ...state,
                            cartProduct: [...state.cartProduct, action.value]
                        }
                    }
                })
            }
            return nextState || state

【问题讨论】:

  • 对于第一篇文章,感谢您展示所有代码。我会在下面告诉你我会做什么。

标签: javascript reactjs react-native redux react-redux


【解决方案1】:

我会做这样的事情。

switch (action.type) {
  case 'ADD_TO_CART':
  const cartProductIndex = state.cartProduct.findIndex(item => item.id === action.value.id)
  if (cartProductIndex == -1) {
    return {
      ...state,
      cartProduct: [...state.cartProduct, action.value]
    }
  }
                
  const newCartProduct = state.cartProduct[cartProductIndex].selectedOption.map(item => {
    if (item.item === action.value.selectedOption.item) {
      item.quantity++
     }
   
     return item
   })                      
   
   return {
     ...state,
     cartProduct: newCartProduct
   }
}  

              

您不能在地图循环中更新状态,地图会返回一个新数组。您想使用 map 创建一个新数组,然后使用该值。一旦一个函数完成你应该返回,你不需要其他的。

【讨论】:

  • 感谢您的帮助,我会尝试您的解决方案,希望它符合我的期望
猜你喜欢
  • 2020-08-19
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多