当React JS中的API状态处于挂起状态时如何显示加载器

时间:2018-11-21 05:51:51

标签: html reactjs api server loader

我的API请求未决时,我必须显示加载程序。我尝试过,但是没有用。那么该怎么做。

this.props.showLoader();
        ajax(config)
            .then((response) => {
                let data;
                this.props.hideLoader();
                data = response.data;
                data[this.props.moduleName.storeVarName + "MediaCost"] = response.data.totalCampaignCost ? response.data.totalCampaignCost : 0;
                this.props.updateCampaignData(data);
            }).catch((error) => {
                this._errorHandler(error);
                this.props.hideLoader();
            });

1 个答案:

答案 0 :(得分:2)

您提供的信息还不够,尽管我正在共享一个示例来显示发出HTTP请求时的加载程序:

const Loader = () => <div>Loading...</div>;

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
    };
  }

  hideLoader = () => {
    this.setState({ loading: false });
  }

  showLoader = () => {
    this.setState({ loading: true });
  }

  fetchInfo = () => {
    const _this = this;
    this.showLoader();
    ajax(config)
      .then((response) => {
        // do whatever you want with success response
        _this.hideLoader();
      }).catch((error) => {
        // do whatever you want with error response
        _this.hideLoader();
      });
  }

  render() {
    return (
      <div>
        <button onClick={this.fetchInfo} />
        {(this.state.loading) ? <Loader /> : null}
      </div>
    );
  }
}