首页 > 解决方案 > 如何在 react-redux 中改变状态?

问题描述

我第一次使用 createSlice 方式来实现 redux,我试图改变商店中的状态,但它不工作并且我正在更新的对象变得未定义。请帮我修一下

[save.fulfilled]:(state,action)=>{
      console.log("inside save it");
      console.log(action.payload,"test");
      console.log(current(state));
      current(state).list.map((C,i)=>{
        console.log(C._id,"ii");
        if(C._id==action.payload._id){
          const temp=Object.assign({},C);
          temp=action.payload.obj
          return temp;
        }
        return C;
      })
      console.log(current(state).list);
    }

如果 id 匹配,我需要改变一个键

Object { form: {…}, _id: "617ce521028ba1920422fb6b" }
​
_id: "617ce521028ba1920422fb6b"
​
form: Object { name: "adarsh hh", email: "adarsh@gmail.com", phone: "8340484685", … }
​

上面是动作对象,下面是状态

Object { list: (2) […], status: "succeeded" }
​
list: Array [ {…}, {…} ]
​​
0: Object { _id: "617ce521028ba1920422fb6b", userid: "616548965d47a2b6ec0a1592", key: 0, … }
​​​
__v: 0
​​​
_id: "617ce521028ba1920422fb6b"
​​​
created: "2021-10-30T06:24:33.922Z"
​​​
form: Object { name: "adarsh raii", email: "adarsh@gmail.com", phone: "8340484685", … }
​​​
key: 0
​​​
updated: "2021-10-30T06:24:33.922Z"
​​​
userid: "616548965d47a2b6ec0a1592"
​​​
<prototype>: Object { … }
​​
1: Object { _id: "617ce5a2028ba1920422fb72", userid: "616548965d47a2b6ec0a1592", key: 0, … }
​​​
__v: 0
​​​
_id: "617ce5a2028ba1920422fb72"
​​​
created: "2021-10-30T06:26:42.600Z"
​​​
form: Object { name: "adarsh raj", email: "adarsh@gmail.com", phone: "8340484685", … }
​​​
key: 0
​​​
updated: "2021-10-30T06:26:42.600Z"
​​​
userid: "616548965d47a2b6ec0a1592"
​​​
<prototype>: Object { … }
​​
length: 2
​​
<prototype>: Array []
​
status: "succeeded"
​
<prototype>: Object { … }

我只想通过匹配_id来改变特定字段对象的表单对象,以便在dom中更新它

标签: javascriptreactjsfrontendmern

解决方案


如果不能改变 redux 状态,则必须复制处理逻辑所需的状态。我认为下面的代码足以满足您的要求让我知道。

[save.fulfilled]:(state,action)=>{
      console.log("inside save it");
      console.log(action.payload,"test");
      console.log(current(state));
      let temp= Object.assign({},current(state));
      temp.list.forEach((C,i)=>{
        console.log(C._id,"ii");
        if(C._id==action.payload._id){
          temp.list[i] = action.payload.obj
        }
       
      })
    return temp; 
      console.log(current(state).list);
    }

推荐阅读