如何在获取拦截器中调度redux动作?

时间:2020-05-05 09:33:21

标签: reactjs react-redux fetch redux-saga

嗨,我有一个访存拦截器来捕获一些常见的响应,例如401等。当响应状态等于401时。我需要在拦截器本身内部调度注销操作。但是我做不到。调度操作不起作用。在这里,我分享了我所做的工作的代码。请帮我解决这个问题。

import fetchIntercept from 'fetch-intercept';
import { pushToDataLayer } from './GTMUtility';
import configureStore from '../redux/configureStore';
import { LoggedOut } from "../redux/auth/actions";


const getEndPointFromURL = (url = '') => {
    if (!url) return;
    const urlSegments = url.split('/')
    return urlSegments[urlSegments.length - 1];
}

const store = configureStore();

export const interceptor = fetchIntercept.register({
    request: function (url, config) {
        return [url, config];
    },

    requestError: function (error) {
        // Called when an error occured during another 'request' interceptor call
        return Promise.reject(error);
    },

    response: function (response) {
        if (response.status === 401) {
            store.dispatch(LoggedOut());
            return false
        }
        return response;
    },

    responseError: function (error) {
        // Handle an fetch error
        return Promise.reject(error);
    }
});

出口商店:

import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./rootReducer";
import createSagaMiddleware from "redux-saga";
import { fromJS } from "immutable";

export default function configureStore(initialState = {}) {
  const sagaMiddleware = createSagaMiddleware();
  const middlewares = [sagaMiddleware];

  const composeEnhancers =
    typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
      })
      : compose;

  return {
    ...createStore(
      rootReducer,
      composeEnhancers(applyMiddleware(...middlewares))
    ),
    runSaga: sagaMiddleware.run
  };
}

谢谢。

1 个答案:

答案 0 :(得分:0)

在拦截寄存器文件中,您还必须导出该存储,以供其他文件使用。如果您还在其他地方调用const store = configureStore(),则将创建一个全新的store实例。然后,拦截器使用的store.dispatch不会影响store的另一个实例,因此是您的问题。

我建议您直接在该文件内创建存储并将其导出,而不是导出configureStore函数。

export const store = configureStore()

然后在拦截器文件中:

import { store } from '../redux/configureStore';

与需要存储的其他文件相同。不再创建它。