React - 在异步操作后立即设置状态

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
  });
})