簡體   English   中英

無法更新狀態內對象的狀態(反應)

[英]Cannot update the state of an object within the state (react)

我的反應應用程序狀態中有一個對象變量。 我使用我希望對象具有的結構對其進行初始化。 晚了,我正在嘗試使用 setState 函數更新該對象。 我的問題是,我無法讓它真正更新該州內的任何內容。 我的代碼目前的樣子是:

// the initial state
var initialState = {
  object: {
   foo: '',
   bar: 0,
   array: [<an array of objects>]
 }
};

// in componentDidMount
this.state = initialState;

// updating the object that is within the state (also in componentDidMount)
let object = {
  foo: 'Value',
  bar: 90,
  array: [<a populated array of objects>]
};
this.setState(prevState => ({
  ...prevState.object,
  ...object
}));
console.log(this.state.object); // returns the object defined in initial state

我真的不知道如何解決這個問題。 我也一直在嘗試其他一些方法(尤其是在這篇文章中概述的那些: 在 React 中使用 setState 更新對象這意味着這是一個不涉及我使用哪種方法的錯誤。任何對此問題的見解將不勝感激。我試圖使此代碼盡可能簡潔,但如果您想查看我正在使用的確切代碼(幾乎就是這個,但更多)只是問。

編輯 2

你必須關心每個對象鍵的相等性。
你可以這樣做。

this.setState((prevState) => {
  console.log('logging state: ', prevState)

 return {
  ...prevState.object,
  object:{ ...object }
  })
)}

暫無
暫無

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

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