使用异步setState [英] Using async setState
问题描述
我有调度动作的功能.我想在操作之前和之后显示一个加载程序.我知道将对象传递给setState
时会做出反应.问题是如何以异步方式更新属性:
I have function which dispatched an action. I would like to display a loader before and after the action. I know that react composing the object passed to setState
. the question is how can I update the property in async way:
handleChange(input) {
this.setState({ load: true })
this.props.actions.getItemsFromThirtParty(input)
this.setState({ load: false })
}
基本上,如果我将此属性作为应用程序状态的一部分(使用Redux),一切都很好,但是我真的更喜欢仅将此属性带到组件状态.
Basically, it all worked great if I put this property as part of the application state (using Redux), but I really prefer to bring this property to the component-state only.
推荐答案
将其余代码包装在第一个setState
的回调中:
Wrap the rest of your code in the callback of the first setState
:
handleChange(input) {
this.setState({
load: true
}, () => {
this.props.actions.getItemsFromThirtParty(input)
this.setState({ load: false })
})
}
这样,可以确保在调用getItemsFromThirtParty
之前将load
设置为true
,并且将load
设置回false
.
With this, your load
is guaranteed to be set to true
before getItemsFromThirtParty
is called and the load
is set back to false
.
这假定您的getItemsFromThirtParty
函数是同步的.如果不是,则将其变成一个承诺,然后在链接的then()
方法中调用最终的setState
:
This assumes your getItemsFromThirtParty
function is synchronous. If it isn't, turn it into a promise and then call the final setState
within a chained then()
method:
handleChange(input) {
this.setState({
load: true
}, () => {
this.props.actions.getItemsFromThirtParty(input)
.then(() => {
this.setState({ load: false })
})
})
}
这篇关于使用异步setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!