简体   繁体   English

Redux + React Native 将产品添加到购物车不起作用

[英]Redux + React Native Add product to cart not working

I'm new to react native and i'm tryin to implement add to cart functionality using redux, It's working when pass the whole product to the cart, but that's not what i'm looking for because i have to add quantity and an input text with every product that user select, (to give the user ability to fill them before checkout).我是本机反应的新手,我正在尝试使用 redux 实现添加到购物车功能,当将整个产品传递到购物车时它正在工作,但这不是我想要的,因为我必须添加数量和输入文本与用户 select 的每个产品,(使用户能够在结帐前填写它们)。 This is the main code (Working fine while passing the whole product)这是主要代码(通过整个产品时工作正常)

const initialState = {
    cart: [],
    total: 0,
}
...
case ADD_TO_CART:
 return {
   ...state,
   cart: [action.payload, ...state.cart],
   total: state.total + action.payload.price
 }
...

This is what i'm trying now这就是我现在正在尝试的

const initialState = {
    cart: [],
    addCart: {
      meal_id: '',
      name: '',
      price: '',
      quantity: 1,
      meal_details: ''
    },
    total: 0,
}
case ADD_TO_CART:
  return {
    ...state,
    addCart: {
     meal_id: action.payload.id,
     name: action.payload.name,
     price: action.payload.price,
     quantity: 1,
     meal_details: ''
    },
    cart: [this.addCart, ...state.cart],
    total: state.total + action.payload.price
 }

But it gives errors, this.addCart add undefined to the cart array, I've tried addCart return can't find variable addCart and i use state.addCart it add first item as null arr and whenever i clicked on another product to add it adds the last one clicked但它给出了错误, this.addCart add undefined to the cart array,我试过addCart return can't find variable addCart 我使用state.addCart它添加第一个项目为 null arr 并且每当我点击另一个产品添加它添加最后一个点击

When accessing the Redux state, there's no this .访问Redux state时,没有this Also, you cannot access properties of an object as you're trying to changing the object, which is also the reason why your main code works but the second snippet does not.此外,当您尝试更改 object 时,您无法访问 object 的属性,这也是您的主要代码有效但第二个代码段无效的原因。 The simplest solution to fix your code will removing addCart from your state, since the data is equivalent to your action.payload , then creating the addCart object separately in the reducer.修复代码的最简单解决方案是从 state 中删除addCart ,因为数据等同于您的action.payload ,然后在减速器中单独创建 addCart object 。

const initialState = {
    cart: [],
    total: 0,
}

case ADD_TO_CART:
  let addCart = {
     meal_id: action.payload.id,
     name: action.payload.name,
     price: action.payload.price,
     quantity: 1,
     meal_details: ''
  }
  return {
    ...state,
    cart: [addCart, ...state.cart],
    total: state.total + action.payload.price
 }

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

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