簡體   English   中英

如何在react-redux中改變狀態?

[英]how to mutate state in react-redux?

我第一次使用 createSlice 方式實現 redux,我試圖改變 store 中的狀態,但它不起作用並且我正在更新的對象變得未定義。 請幫我修復它

[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 中更新它

如果無法改變 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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM