您可以在更高级别的组件中设置axios拦截器,比如 App。您可以使用“SHOW_LOADER”和“HIDE_LOADER”操作类型在减速器中定义加载状态。这些拦截器将在通过axios发送和接收请求之前调度相应的操作,更新存储中的加载状态,您可以通过它呈现加载器组件。
希望这能回答你的问题。
应用组件
import React from 'react';
import axios from 'axios'
import { connect } from 'react-redux';
import { loading } from '../actions'
import Loader from './Loader'
class App extends React.Component{
componentWillMount(){
const self = this
axios.interceptors.request.use(function (config) {
// spinning start to show
self.props.loading(true)
return config
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
// spinning hide
self.props.loading(false)
return response;
}, function (error) {
return Promise.reject(error);
});
}
render(){
return (
<div>
{ this.props.loader ? <Loader /> : null }
{/*
Your other components
*/}
</div>
)
}
}
const mapStateToProps = (state)=>{
return {
loader: state.loader
}
}
export default connect(mapStateToProps,{
loading
})(App);
装载机减速机
const loader = (state = false, action) => {
switch (action.type) {
case "SHOW_LOADER":
return action.data;
break;
case "HIDE_LOADER":
return action.data;
break;
default:
return state;
}
}
export default loader;
行动
export const loading = (bool)=>{
return bool ? {
type:"SHOW_LOADER",
data:bool
}: {
type: "HIDE_LOADER",
data: bool
}
}