簡體   English   中英

在setState中使用變量-反應

[英]Using variable in setState - react

我知道之前也曾問過類似的問題,但是如果我不想將整個狀態(僅其屬性之一)設置為變量,該怎么辦? 像這樣:

 var initialProperty = { name: '', id: 0, type: '' } class Example extends React.Component{ constructor(props){ super(props); this.state = { otherProperty: '', targetProperty: initialProperty //at the start of the Component, everything works fine. //the targetproperty is set to initialproperty } } //by the time, the targetproperty was changed from the initial in the component //but if i click a button, i want to set targetproperty to the initialproperty somethingHappensOnClick = () => { this.setState({targetProperty: initialProperty}) //unfortunately, the targetproperty wasn't set to the initial. } } 

難道我做錯了什么? 為什么targetProperty不變?

發生這種情況是因為在js數組和對象中通過引用復制。 所以當你設置

targetProperty: initialProperty

targetProperty將獲取initialProperty的引用,並且您對targetProperty所做的所有更改也將應用到initialProperty

想法是,每次創建一個新對象,而不是復制引用。

像這樣寫:

var initialProperty = {
  name: '',
  id: 0,
  type: ''
}

class Example extendds React.Component{
  constructor(props){
    super(props);
    this.state = {
      otherProperty: '',
      targetProperty: Object.assign({}, initialProperty) // or {...initialProperty}
    }
  }

  somethingHappensOnClick = () => {
    this.setState({targetProperty: Object.assign({}, initialProperty)})
  }
}

當您設置targetProperty : initialProperty ,會發生什么

initialProperty--->some_memory_location_x
//after doing targetProperty: initialProperty
targetProperty---->some_memory_location_x

因此,當您對targetProperty進行突變時,實際上是在更改some_memory_location_x內存中的值,這也是您的initialProperty指向的位置,因此當再次setState時,您的targetProperty值不會更改,因此請嘗試使用@Mayank Shukla指出的方式你不改變價值

暫無
暫無

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

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