[英]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();
是異步的,因此當我立即設置狀態后,沒有任何變化。 現在,我有第二個按鈕,它引用了第二個功能,可以再次設置狀態。 我想讓這種情況自動發生。 我該怎么辦?
異步動作通常是Promises
或functions 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.