javascript - reducer 正在商店中突然添加商品

标签 javascript reactjs redux react-redux reducers

所以我试图向我的 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
  ]
}

我确信我没有改变状态,提前谢谢您!

最佳答案

不,它们不是凭空而来,您正在主动将值添加到数组中。 您似乎对如何正确处理状态有点困惑。您要么选择不可变的方法(如果您使用 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] 
      },
    };

关于javascript - reducer 正在商店中突然添加商品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65749437/

相关文章:

javascript - 谷歌图表 : How I can disable “Choose a value…” in controlType: CategoryFilter of ControlWrapper

angular - 从 Angular 到 React - 如何将业务逻辑与组件解耦?

javascript - 调度 Action 创建者语法react-redux

reactjs - 未为 deepLink 调用 useEffect 中的函数

javascript - 使用 AngularJS Controller 的 Http 请求

javascript - 动漫js问题(完整功能)

javascript - jQuery 帮助 : How can i hide divisions?

reactjs - 如何在 ReactJS 中共享当前 URL

reactjs - 如何在 Material ui Popper 中输入过渡 Prop

javascript - 如何访问 redux 中 mapDispatchToProps 中的全局状态?