几天来,我一直在解决问题,而我找不到很好的解决方案。
长话短说,每次我发出自定义axios请求时,我只希望屏幕上有一个加载器。我有6个具有拦截器的基本请求实例:
export const axiosRequest1 = axios.create({
//blabla
});
axiosRequest1.interceptors.request.use(
config => {
check();
return config;
},
error => {
return Promise.reject(error);
}
);
axiosRequest1.interceptors.response.use(
config => {
return config;
},
error => {
return Promise.reject(error);
}
);
我需要在此请求中的第一个启动加载程序,并在最后一个请求后删除它。
async function check() {
if (checked === false) {
checked = true;
setTimeout(callback, 699);
}
}
和回调:
function callback() {
isLoading = true;
console.log('---------------');
// and here i want to dispatch my actin from redux store with the value of isLoading.
动作如下:
const setLoader = isLoading => dispatch => {
return dispatch({
type: actionTypes.SET_LOADER,
isLoading: isLoading
});
}
export default setLoader;
我通常会导出我的商店并致电操作创建者,除非商店声明是这样的。
const initStore = previousStore => {
return createStore(//bla);};
因此,如果我尝试这样做,将会创建新的商店,这是我不想要的。
有人知道我该如何解决吗?
答案 0 :(得分:0)
我已经实现了处理全局未授权请求的逻辑,但是我认为您也可以将其用于您的案例。只需使用axios全局拦截器即可。这是一个示例:
import React from 'react';
import axios from 'axios';
import {render} from 'react-dom';
import {BrowserRouter as Router, Route} from 'react-router-dom';
// Redux binders
import {Provider} from 'react-redux';
// Our data store
import reduxStore from './store';
import App from './components/App';
const router = (
<Provider store={reduxStore}>
<Router>
<Route path="/" component={App}/>
</Router>
</Provider>
);
import {didFireRequest, didFinishRequest} from './actions/global';
const {dispatch} = reduxStore;
/** Intercept outgoing requests and update loading indicator state. **/
axios.interceptors.request.use(
config => {
dispatch(didFireRequest());
return config;
},
error => {
dispatch(didFinishRequest());
return Promise.reject(error);
}
);
/** Intercept all responses update loading indicator state. **/
axios.interceptors.response.use(
response => {
dispatch(didFinishRequest());
return response;
},
error => {
dispatch(didFinishRequest());
return Promise.reject(error);
}
);
render(router, document.getElementById('app-root'));