【问题标题】:Redux reducer is not returning the entire stateRedux reducer 没有返回整个状态
【发布时间】:2020-11-10 11:54:43
【问题描述】:

我是redux的新手,我的问题是当我派发动作时,它会进入reducer但状态没有更新。

这是我的初始状态

   const initialState ={
    cart :[ ],
    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 UPDATE_QUANTITY:
              
                return{
                    ...state,
                    cart:state.cart.map((product,i) =>
                    {
                        if(i === (action.product.id-1))
                       {
                           return{product.quantity = action.qty.toString()}
                         

                       }
                           return product
                       
                        
                    })
                } 

其他 reducer 工作正常并返回正确的状态,但是当我发送此操作时,我的状态没有更新。如果对代码有任何改进。请说明

【问题讨论】:

  • 地图函数中没有返回任何内容。

标签: reactjs redux reducers


【解决方案1】:

你需要从地图返回:

case UPDATE_QUANTITY:
  return {
    ...state,
    cart: state.cart.map((product) => {
      if (product.id === action.product.id) {
        return {...product, quantity: action.qty.toString()}
      }
      return product;
    })
  }

【讨论】:

  • 我试过了,但是没用,顺便说一句,你为什么要使用传播产品
  • 究竟是什么不起作用?对象分布在那里,因此原始对象不会发生变异,因为在 Redux 中这样做会产生不希望的副作用。
  • 我已经用你的代码编辑了我的代码,但是在状态为空的地方仍然存在同样的错误
  • 问题很可能出现在代码的其他部分。还更新了答案,通过 id 而不是数组索引来匹配产品,这样更可靠。
  • 感谢@clarity,您的代码运行良好,没有任何错误,但您能否解释一下代码,因为我无法理解发生了什么。为什么你使用 return {...product, quantity: action.qty.toString()} 并在你使用 return product 的 if 语句之后再次使用。请解释代码。提前谢谢
猜你喜欢
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 2020-05-23
  • 2023-03-23
相关资源
最近更新 更多