我有一个 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 请求的完成,然后将数据传递给视图组件中的回调进行渲染;以便从动画组件中抽象出提升,但处理事件的调度或任何可能的事件。
我怎样才能做到这一点?