在 React 类组件中设置操作前后的加载状态 [英] Set loading state before and after an action in a React class component
问题描述
我有分派动作的函数.我想在动作之前和之后显示一个加载器.我知道反应组合传递给 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 })
})
}
这样,您的 load
保证在 getItemsFromThirtParty
被调用和 load
之前设置为 true
设置回 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
函数是同步的.如果不是,则将其转换为 promise,然后在链接的 then()
方法中调用最终的
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 })
})
})
}
这篇关于在 React 类组件中设置操作前后的加载状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!