簡體   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