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

问题描述 投票:0回答:1

有些日子我一直围绕着一个问题,我找不到一个好的解决方案。

长话短说,我只想在每次制作自定义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);};

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

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

reactjs redux axios
1个回答
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'));
© www.soinside.com 2019 - 2024. All rights reserved.