簡體   English   中英

反應-異步操作后立即設置狀態

[英]React - Setting state immediately after an async action

所以我有一個按鈕。 當您單擊該按鈕時,它將帶您進入如下所示的onSubmit函數:

  onSubmit(e) {
      e.preventDefault();
      this.props.nextSentence(); //this is async

      this.setState({ //this is not yet updating with the right values then
          inputField: this.props.activePupil.name
      });
  }

但是: this.props.nextSentence(); 是異步的,因此當我立即設置狀態后,沒有任何變化。 現在,我有第二個按鈕,它引用了第二個功能,可以再次設置狀態。 我想讓這種情況自動發生。 我該怎么辦?

異步動作通常是Promisesfunctions with callbacks

如果是Promise ,則需要使用.then如下所示

this.props.nextSentence().then(() => {
  this.setState({...});
})

並且在function with callback情況下

this.props.nextSentence(() => {
  this.setState({...})
})

但是請記住,您可以獲得異步操作的返回響應並使用它來更新狀態。 這是通常的情況。

例如

//here response is a json object returned from server     
this.props.nextSentence().then((response) => {
  this.setState({
    data: response.data
  });
})

暫無
暫無

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

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