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

查看:68
本文介绍了在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 })
  })
}

使用此方法,可以确保在调用 getItemsFromThirtParty load 之前,将 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 函数是同步的.如果不是,则将其变成一个承诺,然后在链接的 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天全站免登陆