我是新来的反应者,本机反应。我正在尝试使用Axios拦截器显示HTTP请求的全局加载指示器。我在我的应用程序中使用redux。但是问题是,无论何时我在我的应用程序(在其他组件,例如App组件)中进行HTTP调用时,加载指示器都不会显示。
我做错了什么?这是流程
HttpLoading
的单独组件来显示加载程序。该组件使用mapStatetoProps从redux获取状态HttpLoader
组件导入到主App组件中但是,如果我在App组件或任何其他组件中发出HTTP请求,则不会显示加载程序。我的目标是为所有HTTP请求显示一个全局加载器。
谢谢。
axios.ts
import axios from 'axios'
import store from '../redux/store';
import { START_LOADING, FINISH_LOADING } from '../redux/types/loadingTypes'
axios.interceptors.request.use(async function (config) {
// Do something before request is sent
console.log("show loading")
store.dispatch({type : START_LOADING, payload : true})
return config;
}, function (error) {
console.log(error)
store.dispatch({type : FINISH_LOADING, payload : false})
console.log("finish loading")
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
store.dispatch({type : FINISH_LOADING, payload : false})
console.log("finish loading")
return response;
}, function (error) {
store.dispatch({type : FINISH_LOADING, payload : false})
console.log("finish loading")
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
loadingType.ts
export const START_LOADING = 'START_LOADING'
export const FINISH_LOADING = 'FINISH_LOADING'
loadingAction.ts
import { START_LOADING , FINISH_LOADING } from '../types/loadingTypes'
export const Loading_action = (bool : boolean)=>{
return bool ? {
type: START_LOADING ,
data:bool
}: {
type: FINISH_LOADING ,
data: bool
}
}
loadingReducer.ts
import { START_LOADING, FINISH_LOADING, Loading , LoadingActions } from '../types/loadingTypes'
const initialState : Loading = {
active_loading : 0,
}
const loadinReducer = (state = initialState, action : LoadingActions) => {
switch(action.type) {
case START_LOADING : {
state.active_loading++;
return action.payload
}
case FINISH_LOADING : {
state.active_loading--;
return action.payload
}
default : return state
}
}
export default loadinReducer
App.tsx
import './shared/axiosInterceptor'
import { Provider } from 'react-redux'
import store from './redux/store'
// other imports
return (
<>
<Provider store={store}>
<AuthLoading />
<HttpLoading />
</Provider>
</>
);
};
export default App
httpLoading.tsx // HTTP加载组件
import { Loading_action } from '../redux/actions/loadingActions'
// other imports
const HttpLoading: React.FC<props> = ({ loading }) => {
return (
loading.active_loading > 0 ?
<View style={styles.horizontal}>
<ActivityIndicator size="large" color="#00ff00" />
</View> : null
)
}
const mapStateToProps = (state: RootState) => ({
loading: state.loading,
});
export default connect
(mapStateToProps, { Loading_action })
(HttpLoading)