繁体   English   中英

使用 redux 响应原生购物车

[英]react native shopping cart with redux

您好,我刚刚开始使用 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

我会做这样的事情。

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 创建一个新数组,然后使用该值。 一旦一个函数完成,你应该返回,你不需要其他的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM