[英]What is the best way to create a Loading Animation for React JS Ajax calls?
我有一个 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 的某种组合才能做到这一点。 我只是无法弄清楚这个出现的正确流程/顺序。
为了使其可重用,我将让组件显示 animation,监听 ajax 请求的完成,然后将数据传递给视图组件中的回调进行渲染; 以便从 Animation 组件中抽象出提升,但处理事件的调度或任何可能的事件。
我怎样才能做到这一点?
我不确定我是否得到了可重复使用的部分。 处理加载最直接的方法是在 state 中处理它(如下所示)。 我不知道它是否适合您:
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>
<>
);
}
}
如果你想在不同的地方重复使用它,你最好寻找一种方法来将负载 state 分散在你想重复使用的组件和地方。 对于这种情况,您可以使用 redux 或通量库来处理 state。 还有内置的上下文 API 也可能有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.