【问题标题】:React - Setting state immediately after an async actionReact - 在异步操作后立即设置状态
【发布时间】:2017-03-29 11:32:04
【问题描述】:

所以我有一个按钮。当您单击该按钮时,它会将您带到一个如下所示的 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(); 是异步的,所以当我立即设置状态时,没有任何变化。现在我有第二个按钮,它指的是第二个功能,它只是再次设置状态。不过,我希望这种情况自动发生。我怎么能这样做?

【问题讨论】:

  • 你为什么不想要结果然后设置状态?使用 then(...) this.props.nextSentence.then(value => this.setState ({ ... }))
  • 也许您可以尝试将您的状态设置为道具并在包含回调 nextSentence 的父级中更改它?
  • 你可以使用 Promise 来处理这种情况

标签: javascript reactjs react-native react-redux


【解决方案1】:

异步操作通常是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
  });
})

【讨论】:

  • 谢谢。 However keep in mind than you can get the returned response of your async action and use it to update your state. which is normally the case. - 这与使用承诺或回调有何不同?
  • 就像我提供的例子一样,你只是使用你的异步方法响应来改变你的状态。
猜你喜欢
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多