在我的React组件通过AJAX进行抓取时,显示加载Spinner/gif的最佳方法? [英] Best way to show a loading spinner/gif while my React component is fetching via AJAX?

查看:39
本文介绍了在我的React组件通过AJAX进行抓取时,显示加载Spinner/gif的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个非常简单的React组件,它显示了存储在 this.state.myList 中的元素列表(请参见下面的示例)

Imagine I have a very simple React component that shows a list of elements that are stored in this.state.myList (see example below)

点击底部的刷新"按钮会导致React查询后端服务器并检索更新的列表,然后将其显示.此列表的实际内容或实现无关紧要.

Hitting a "Refresh" button at the bottom causes React to query the backend server and retrieve an updated list that it will then display. The actual contents or implementation of this list are irrelevant.

var Foo = React.createClass({
  handleButtonClick: function() {
    return $.ajax({
      type: "POST",
      url: "/some/refresh/url",
      data: JSON.stringify({}),
      dataType: "json",
      contentType: "application/json",
      success: (function(response){
        self.setState({ myList: response.list });
      })
    });
  },

  render: function() {
    return (
      <div className="container">
        <ul>
          {
            this.state.myList.map(function(item) {
              return <li id="{item.id}">{item.name}</li>
            });
          }
        </ul>

        <input type="submit" value="REFRESH LIST" onClick={this.handleButtonClick} />
      </div>
    );
  }
});

让我们说AJAX调用(无论出于何种原因)要花费几秒钟.在此期间,我希望显示一个标准的加载"或旋转" gif,以使用户知道它正在工作.

Let's say the AJAX call (for whatever reason) takes a few seconds. In that meantime, I'd love to show a standard "loading" or "spinner" gif to let the user know it's working.

在这里这样做的最佳方法是什么?

What's the best approach to doing that here?

  • 就在AJAX调用之前,我可以手动更新DOM并插入微调gif,但这似乎不是反应的方式".而且我不知道这会对React维护的ReactDOM产生什么影响.

  • Right before the AJAX call I could manually update the DOM and insert a spinner gif but that doesn't seem like the "React way to do it". And plus I don't know what impact that would have on the ReactDOM that react maintains.

我可以跟踪 isLoading 的状态,并显示微调框而不是列表(如果正在加载).但是然后我需要它来 render()一些东西,然后立即启动另一个对AJAX动作的调用.

I could track a state for isLoading and show the spinner instead of the list if it is loading. But then I would need it to render() something and then immediately kick off another call to an AJAX action.

任何帮助表示赞赏.

谢谢!

推荐答案

我始终解决此问题的方法是使组件在其状态下跟踪 fetchInProgress .

The way I always solve this is for the component to track fetchInProgress in its state.

在进行提取之前,请将此值设置为 true ;提取完成(成功或失败)后,将值设置回 false .

Before you make your fetch, you set this value to true; when the fetch completes (either success or fail), you set the value back to false.

然后组件的 render 方法接受此标志;如果该标志为 true ,则呈现一个微调框而不是数据集.

The component's render method then honors this flag; if the flag is true, it renders a spinner instead of a dataset.

var Foo = React.createClass({
    handleButtonClick: function() {

        // before making call, set fetch flag
        self.setState({ fetchInProgress: true });

        return $.ajax({
            type: "POST",
            url: "/some/refresh/url",
            data: JSON.stringify({}),
            dataType: "json",
            contentType: "application/json",
            success: (function(response) {
                // when updating with dataset, also reset fetch flag
                self.setState({
                    fetchInProgress: false,
                    myList: response.list
                });
            }),
            failure: ((function(reason) {
                // make sure to reset even if fetch fails!
                self.setState({
                    fetchInProgress: false
                });
            })
        });
    },

    render: function() {
        return (
            <div className="container">
                <ul>
                    {
                        this.state.fetchInProgress
                            : <Spinner />
                            : this.state.myList.map(function(item) {
                                    return <li id="{item.id}">{item.name}</li>
                                })
                    }
                </ul>

                <input type="submit" value="REFRESH LIST" onClick={this.handleButtonClick} />
            </div>
        );
    }
});

这篇关于在我的React组件通过AJAX进行抓取时,显示加载Spinner/gif的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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