【问题标题】:Reducer is adding items in the store out of nowhereReducer 突然在商店中添加商品
【发布时间】:2021-04-21 06:28:57
【问题描述】:

所以我试图在我的 React-redux 网站上添加一个购物车功能,但我遇到了一个非常奇怪的情况。所以这就是我从动作的有效负载中得到的,例如:

{
    info: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
    id: 1,
    price: 109.95,
    image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
    count: 5,
    totalPrice: 549.75
 }

所以我要做的是,当尝试添加与此 id 相同的商品时,不要添加它,而是增加购物车中已存在的具有相同 id 的商品的数量:

const index = state.currentCart.findIndex((x) => x.id === id);
return {
          ...state,
          currentCart: [
            ...state.currentCart,
            state.currentCart[index].count += 1,
             (state.currentCart[index].totalPrice =
              state.currentCart[index].price * state.currentCart[index].count), 
          ],
        };

计数本身增加了,但同时发生了一些非常奇怪的事情。 产品的总价格及其计数也作为 currentCart 数组的元素添加,当唯一应该发生的事情是使用有效负载中的 id 更新购物车项目的计数时, 这是触发此操作时 currentCart 数组发生的情况:

currentCart: [
    {
      info: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
      id: 1,
      price: 109.95,
      image: 'https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg',
      count: 6,
      totalPrice: 659.7
    },
    2,
    219.9,
    3,
    329.85,
    4,
    439.8,
    5,
    549.75,
    6,
    659.7
  ]
}

我确定我没有改变状态,提前谢谢你!

【问题讨论】:

  • 你在说currentCart数组中的奇怪值?喜欢2, 219.9,
  • 是的,没错,它只是突然出现,或者我做错了什么。
  • 尝试删除return 语句中的这一行,然后重试(state.currentCart[index].totalPrice =state.currentCart[index].pricestate.currentCart[index].count),
  • 嘿,对不起,我把退货复制错了,我修好了,你能再看看吗
  • hmmm... 尝试将您的设置调用封装在 {} 中。 currentCart:[...state.currentCart,{state.currentCart[index].count += 1, and remaining setter}].

标签: javascript reactjs redux react-redux reducers


【解决方案1】:

不,它们不是凭空而来的,您正在积极地将值添加到数组中。 您似乎对如何正确处理状态有点困惑。你要么选择不可变的方法(如果你使用 react,我真的建议你这样做)或者你选择改变你的引用。

在 javascript 中,当您进行赋值时,该赋值也会返回被赋值的值,例如这里:

let x = 1
let b = x+=1
// b is now 2 and x is 2
let c = b += 2
// b is now 4 and c is also 4

这正是您的数组分配发生的情况。您首先将旧版本的数组传播到新版本(制作副本)上,然后同时改变对当前汽车的引用(这是关键部分),您正在保存那些的返回值数组本身的赋值。 看看数组上的值,它们是你操作的结果:

count (1) += 1 // 2
price (109.95) * count (2) = 219.9,
count (2) += 1 // 3
price (109.95) * count (3) = 329.85
... etc

因此,您的阵列上的内容是计数和总价格值的历史记录。

这是您代码中发生的情况的细分:

// Will allways be at index 0, because you add it as first element 
// and then you keep copying the array below
const index = state.currentCart.findIndex((x) => x.id === id); 
return {
          ...state,
          currentCart: [
            // Here you are copying the old array into the new one,
            // keeping the current car at the first position 
            ...state.currentCart,
            // Here you are updating the values of the object at index 0
            // and at the same time you are adding those values at 
            // the end of the array
            state.currentCart[index].count += 1,
             (state.currentCart[index].totalPrice =
              state.currentCart[index].price * state.currentCart[index].count), 
          ],
        };

您要做的是每次都构建一个新的 currentCart 。您还想为 currentCart 使用对象,而不是数组。如果您想在购物车中保留商品列表,我建议您在购物车上创建一个名为 items 的嵌套属性,并将其设为数组。 您的代码示例并未向我们展示您从何处获取操作,但我会为您提供一个示例,假设您刚刚拥有它并且要添加到购物车的新商品位于有效负载中。

  const currentCart = state.currentCart;
  const newItem = action.payload
  return {
      ...state,
      currentCart: {
        ...currentCart,
        count: currentCart.count + 1
        totalPrice: (newItem.price * newItem.count) + currentCart.totalPrice,
        items: [...currentCart.items, newItem] 
      },
    };

【讨论】:

  • currentCart 最初是一个初始状态的空数组,但是你在动作中将它作为 currentCart: {} 返回,这是我在你的例子中不明白的东西,你能解释一下,请。
  • 您应该将 currentCar 更改为初始状态下的空数组。您使用它的方式将它作为一个数组是没有意义的。一个数组是有一个项目列表,但 currentCar 看起来它是一个单一的实体,因此你不需要一个数组。我将修复代码以删除所有数组引用。
  • 它是一个数组,因为我随后在带有 .map 的组件中使用它来加载购物车项目
  • 您必须分享有关您的代码的更多详细信息,但如果您希望它成为当前汽车的列表(您从未解释过),您最好以复数形式命名。此外,您向我们展示的代码不是向数组中添加新车,它只是更新第一个
  • 我最终采用了另一种方式,但我仍会将其标记为解决方案,因为我感谢您花时间解释并向我展示我做错了什么:)
【解决方案2】:

我不确定,但这正在发生
totalPrice = 商品价格 * 添加商品的次数

不包括其他商品的价格。试试这个 -

state.currentCart[index].totalPrice += state.currentCart[index].price * state.currentCart[index].count

(只是 '+=' 而不是 '=')

【讨论】:

  • 原来是这样的,后来改成'=',结果都一样……
猜你喜欢
  • 1970-01-01
  • 2021-09-27
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多