1

我有一个 React JS (16.13.1) 应用程序——我有兴趣创建一些加载动画,以便在加载内容时在容器中显示。我希望以一种可以提供一些可重用性的方式来做到这一点,如下例所示:

import React from "react";
...
import axios from "axios";
import LoadingAnimation from "[myloadinganimation]"

class Widget extends React.Component {
    constructor(props) {
        super(props);
        this.state = { widgets: [] };
    }

    getWidgets() {
        const data = new FormData();
        return axios.post('/my/api/url', data, window.globals.formPostHeaders)
               .then(res => {
                    const regions = res.data.regions.map(obj => obj);
                    this.setState({regions});
               });
        
    }


    render() {
         return (
              <>
                 <Table>
                     <tbody>
                     <tr>
                         <!-- desired component -->
                         <LoadingAnimation self={this} conds={{obj: this, cb: 'callback?'}} />
                         <!-- /desired component -->
                     </tr>
                     </tbody>
                 </Table>
              <>
         );

    }

}

理论上,我会拥有一个名为 LoadingAnimation 的组件,可以在此页面上调用它——最好是在页面加载时,或者甚至只是在启动 AJAX 请求时调用。我意识到这需要侦听器、回调和 Promise 的某种组合才能做到这一点。我只是无法弄清楚这个出现的正确流程/顺序。

为了使其可重用,我会让组件显示动画,监听 ajax 请求的完成,然后将数据传递给视图组件中的回调进行渲染;以便从动画组件中抽象出提升,但处理事件的调度或任何可能的事件。

我怎样才能做到这一点?

4

1 回答 1

0

我不确定我是否得到了可重复使用的部分。处理加载最直接的方法是在状态中处理它(如下所示)。我不知道它是否适合您:

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

  componentDidMount() {
    // to trigger on page load
    this.getWidgets()
  }

  async getWidgets() {
    this.setState({ loading: true})
    const data = new FormData();
    await axios.post('/my/api/url', data, window.globals.formPostHeaders)
      .then(res => {
        const regions = res.data.regions.map(obj => obj);
        this.setState({ regions });
      });
    this.setState({ loading : false})
  }


  render() {
    return (
            <>
              <Table>
                <tbody>
                  <tr>
                    { this.state.loading && <LoadingAnimation />}
                  </tr>
                </tbody>
              </Table>
            <>
          );
       }
}

如果你想在不同的地方重用它,你最好寻找一种方法来将加载状态分散到组件和你想重用的地方。您可以使用 redux 或 Flux 库来处理此类情况的状态。还有内置的 Context API 也可能有用。

于 2020-06-23T05:43:44.483 回答