在 React 类组件中设置操作之前和之后的加载状态 [英] Set loading state before and after an action in a React class component

查看:23
本文介绍了在 React 类组件中设置操作之前和之后的加载状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有调度一个动作的函数.我想在操作之前和之后显示一个加载器.我知道反应组成传递给 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 })
  })
}

这样,在调用 getItemsFromThirtPartyload 之前,保证您的 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() 方法中调用最终的 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 })
      })
  })
}

这篇关于在 React 类组件中设置操作之前和之后的加载状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆