簡體   English   中英

如何在 setState 中使用破壞?

[英]How to use destructing in setState?

我正在研究反應。 當我像這樣編寫代碼時,由於異步,console.log 無法正確捕獲 input.value。 (時間問題)

handleInput = (e) => { 
  this.setState({
   text: e.target.value
  }); 
  console.log(this.state.text); 
}

所以我像這樣修復了它,並且效果很好。

handleInput = (e) => { 
  this.setState({
   text: e.target.value
  },
  () => {console.log(this.state.text)}
 );
}

然后,我嘗試像這樣破壞,但它再次無法正常工作。

handleInput = (e) => { 
  const {text} = this.state;
  this.setState({
   text: e.target.value
  },
  () => {console.log(text)}
 );
}

所以我像這樣修復了它,並且效果很好。 我認為這也是異步的原因,但我不確定。

handleInput = (e) => {  
  this.setState(
  {
   text: e.target.value
  },
  () => {
   const {text} = this.state;
   console.log(text);
  }
 );
}

所以我的問題是,如果我想在 setState() 中使用破壞,我應該每次都寫這樣的代碼嗎? 我的意思是,總是在 setState 內部使用破壞?

這是我在反應文檔中發現的:

setState() 並不總是立即更新組件。 它可能會批量更新或將更新推遲到以后。 這使得在調用 setState() 之后立即閱讀 this.state 是一個潛在的陷阱。 相反,使用 componentDidUpdate 或 setState 回調 (setState(updater, callback)),它們都保證在應用更新后觸發。

這是您在第一次修復中所做的,這是正確的方法。

現在在你的第二個問題

handleInput = (e) => { 
  const {text} = this.state;
  this.setState({
    text: e.target.value
   },
   () => {console.log(text)}
  );
}

您正在對 handleInput 方法進行解構,因此 setState() 回調無法使用該值,因為它不會以與您閱讀代碼相同的順序執行。 您修復它的方式應該可以正常工作,因為您使用的是箭頭 function 並且您不需要將“this”綁定到方法,因此它應該可以訪問相同的“this”實例。

現在開始解構,何時使用它完全取決於您。 在某些情況下,它可以使您的代碼看起來更干凈,但並不總是有意義。

如果你真的看這段代碼。 您尚未在setState function 的回調中破壞state

handleInput = (e) => { 
  const {text} = this.state;
  this.setState({
   text: e.target.value
  },
  () => {console.log(text)}
 );
}

您已將它移到下面的回調中並且它起作用了,

handleInput = (e) => {  
  this.setState(
  {
   text: e.target.value
  },
  () => {
   const {text} = this.state;
   console.log(text);
  }
 );
}

希望這能把事情弄清楚!

您在第三個示例中解構 state 的方式,它將得到以前的 state 而不是當前的 state。 要在更新后獲取 state,您需要使用第二個回調setState或者您可以使用componentDidUpdate

另外,您還可以解構event object,如下所示:

handleInput = ({ target: { value: text } }) => {
  this.setState({ text }, () => {
    const { text } = this.state;
    console.log(text);
  });
};

但是根據我的說法,破壞並不總是必要的,如果它不能使代碼更具可讀性和可維護性,那么使用它就沒有意義。

它與async無關。

您不必以這種方式進行Object 解構 保持handleInput簡單。

handleInput = (e) => this.setState({text: e.target.value})

您可以 object 在您想要的任何地方解構。

更好的方法之一是使用componentDidUpdate

componentDidUpdate(prevState) {
    const prevText = prevState.text
    const {text} = this.state
    console.log(prevText, text)
}

在這種情況下,由於 state 的設置是一個異步任務,並且在觸發 setState function 后,您需要“text”變量的最新值,因此您需要從回調 ZC1C425Z0741AB7A85D14 內部析構其值

Whereas if you just need the state value and do not need to update the state before getting that state value, you can destructor the "text" value from anywhere in your code without the need for the callback function.

暫無
暫無

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

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