【问题标题】:update same state twice in react redux在 react redux 中更新相同的状态两次
【发布时间】:2020-11-10 20:10:00
【问题描述】:

如何在同一个 reducer 中两次更新我的状态

我在 redux 商店中的状态

const initialState = {
 cart:[] as any ,
   Products:[
     {
       id: "1",
       title: "Realme 3 pro",
       image: {
         img1: "https://www.monotain.com/wp-content/uploads/2019/12/realme-5-pro.jpg",
         img2: "https://static.techspot.com/images/products/2019/smartphones/org/2019-05-20-product-7.jpg"
       },
       price: "10000",
       details: "Take photography a notch higher with the Realme 3 Pro as it comes with a 25 MP AI Selfie Camera and 16 MP + 5 MP Rear Camera with Sony IMX519 Sensor. The Qualcomm Snapdragon 710 AIE, multi-core AI Engine and Adreno 616 GPU redefine your smartphone experience.",
       seller: "Cloudtail India",
       quantity: 0
     }
   ],

我的用于更新状态的减速器

case ADD_TO_CART :
  let num = parseInt(action.product.quantity) + 1
  console.log(num)
  if (state.cart.includes(action.product)) {
    alert("Please increase the product at cart page");
  } else {
    return {
      ...state,
      cart: state.cart.concat(action.product)    
    }
  }

这里我想将 product 更新为 cart state 并且我想增加同时更新到cart 的数量

【问题讨论】:

    标签: reactjs redux reducers


    【解决方案1】:

    代替警报,尝试:

    const updatedCart = {...cart}
    updatedCart.find(i => i.id === action.product.id).quantity +=1
    return {
          ...state,
          cart: updatedCart
    }
    

    【讨论】:

    • 我不知道您是如何设置 redux 的其余部分的,因为您在问题中没有提到它,但是您应该能够通过输入该代码来更新您的方法中的状态(或类似的东西)而不是 if 语句中的警报。
    • 我写的代码正在更新状态,它工作得很好,我想要的是在将产品存储到购物车后更新数量。请提供此代码
    • 你上面写的代码只是alerts用户。此答案中的代码将按照您的要求在购物车中查找产品、增加数量并更新购物车状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 2017-05-12
    • 2021-01-08
    相关资源
    最近更新 更多