reactjs - 使用 Axios 和 React 显示加载微调器(可能是 Redux)
问题描述
我的目标是在调用 http 请求时显示加载微调器。我想在全局范围内执行此操作,这意味着,当任何组件调用某个 api 时,会自动显示微调器,最好没有额外的代码来控制微调器。
我正在使用反应和 axios。我知道 axios 的拦截器。
我的实际结构:
<Component App>
<Component A />
<Component B />
<Loading Component>
</Component App>
我不知道是否有可能做出反应,但我尝试制作一个通用类来实现有关服务的基本信息,例如 baseUrl 和 http 拦截器。因此,当需要调用 API 服务时,我使用通用类创建一个专门的类,并将该概念中的所有 api 方法集中在那里,然后使用基类调用 axios 方法 get、post 等。因此,拦截器出现并在请求之前显示微调器并在请求之后隐藏。
这个想法是一个组件调用专用类来调用 API 并显示微调器,直到请求运行。
我想用redux来使状态是全局的,但我不知道是否可以在一个类中实现(API Class Base和Specialized API Class)
我的问题: - 是否可以使用这种架构?- 如果是,如何实现和使用 redux?- 使用类的权利还是更好地使用组件来实现基本服务类和专用类?
应用组件:
class App extends Component {
constructor(props) {
super(props);
this.state = {
rows: []
};
}
componentDidMount() {
var service = new specializedService();
var response =
specializedService.someAPIMethod(1).then((res) => {
this.setState({
rows: res.data
});
});
}
render() {
return (
<div className="App">
<Component A rows={this.state.rows} />
<Component B rows={this.state.rows}/>
<Loading />
</div>
);
}
专业服务:
import serviceBase from "./serviceBase";
class specializedService {
someAPIMethod(id) {
return serviceBase.get('someMethod/' + id);
};
}
服务基础:
import axios from "axios";
const serviceBase = () => {
const api = axios.create({
baseURL: 'https://xxxxx.xxxxx.com/xxxxxx/'
});
api.interceptors.request.use(async (config) => {
try{
// In this moment, show the spinner
// showLoading();
}
catch(e)
{
alert('Error request' + e);
}
return config;
});
api.interceptors.response.use(async (config) => {
try {
// In this moment, hide the spinner
// hideLoading();
}
catch(e)
{
alert('Error response' + e);
}
return config;
});
return api;
};
export default serviceBase;
我做了一个简单的例子来说明情况,但是我没有连接redux https://repl.it/@DiegoFerreira1/LoadingSpinnerApp
解决方案
这使用 redux 和 thunk 非常方便。
但是,你可以使用类似的黑客,
this.state = {
rows: [],
isLoading: false,
}
apiCallFunction = () => {
this.setState(prevState => ({ isLoading: !prevState.isLoading }) // to be true..
// api call..
// upon response success =>
this.setState(prevState => ({
isLoading: !prevState.isLoading, // to be false..
rows: prevState.rows = response json,
})
}
在渲染中,
render () {
return (
{isLoading && <Spinner />}
{... handle the rest}
)
}
推荐阅读
- java - 数据库更新后模型类出现问题,
- google-chrome - 在 Chrome 上伪造 USB 设备
- mysql - 尝试增加 MariaDB 值
- python - 在条件语句中使用时间作为参数
- visual-studio-code - 无法使用 html 文件将样式应用于 VSCode Webview
- ubuntu - Meteor Svelte 找不到我在 Ubuntu 上创建的文件
- ubuntu - 如何使用 udev 规则自动挂载 USB 块设备?
- travis-ci - 在 GitHub 操作上使用 dpl
- java - 三星键盘退格键不适用于 SearchView
- php - 如何以智能的方式使用 PHP PDO 显示来自 PostgreSQL 的图像