所以我有一个按钮。当您单击该按钮时,它会将您带到如下所示的 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();
是异步的,所以当我之后立即设置我的状态时,没有任何变化。现在我有第二个按钮,它指的是第二个功能,它只是再次设置状态。不过,我想让这一切自动发生。我怎么能这样做?
最佳答案
异步操作通常是Promises
或带回调的函数
。
如果是 Promise
,您需要使用 .then
,如下所示
this.props.nextSentence().then(() => {
this.setState({...});
})
如果是回调函数
this.props.nextSentence(() => {
this.setState({...})
})
但是请记住,您可以获得异步操作的返回响应并使用它来更新您的状态。通常是这种情况。
例如
//here response is a json object returned from server
this.props.nextSentence().then((response) => {
this.setState({
data: response.data
});
})
关于javascript - React - 在异步操作后立即设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43092299/