从非 redux 组件中的 redux 存储中调度操作



几天来,我一直在思考一个问题,但我找不到一个好的解决方案。

长话短说,每次我发出自定义 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);};

因此,如果我尝试这样做,将创建一个新商店,这是我不想要的。

有没有人知道我该如何解决这个问题?

我已经实现了这个逻辑来处理全局未经授权的请求,但我认为您也可以将其用于您的情况。只需使用 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'));

最新更新