首页 > 解决方案 > 在 axios 拦截器中调度其他操作时忽略 Redux 操作负载

问题描述

我需要checkConnection在任何其他操作之前调用,所以我想到了使用 axios 拦截器:

axios.interceptors.request.use(
  async config => {
    await store.dispatch(checkConnection())

    const { requestTime, hash } = intro(store.getState())

    return {
      ...config,
      headers: {
        'Request-Time': requestTime,
        'Api-Hash-Key': hash
      }
    }
  }
)

introserverTime是一个重选选择器,用于在(serverTime 是 checkConnection 的结果)上进行一些“繁重”计算

checkConnection是一个 redux thunk 动作:

export const checkConnection = () => async (dispatch, _, {
  Intro
}) => {
  dispatch(introConnectionPending())

  try {
    const { data: { serverTime } } = await Intro.checkConnection()

    dispatch(introConnectionSuccess(serverTime))
  } catch ({ message }) {
    dispatch(introConnectionFailure(message))
  }
}

因此,现在每次我调度一个调用 API 的操作时,checkConnection都会先运行。

问题是当负责调度的主要操作(而不是 checkConnection)类型的减速器被调用时,它甚至看不到有效负载。

下面是一个动作示例:

export const getData = () => async (dispatch, getState, {
  API
}) => {
  dispatch(dataPending())

  const credentials = getUsernamePasswordCombo(getState())

  try {
    const { data } = await API.login(credentials)

    dispatch(dataSuccess(data))
  } catch ({ message }) {
    dispatch(dataFailure())
  }
}

及其减速器:

export default typeToReducer({
  [SET_DATA]: {
    PENDING: state => ({
      ...state,
      isPending: true
    })
  },
  SUCCESS: (state, { payload: { data } }) => ({
    ...state,
    isPending: false,
    ...data
  }),
  FAILURE: state => ({
    ...state,
    isPending: false,
    isError: true
  })
}, initialValue)

标签: reduxaxiosinterceptor

解决方案


减速机是完全错误的。它应该是:

export default typeToReducer({
  [SET_DATA]: {
    PENDING: state => ({
      ...state,
      isPending: true
    }),
    SUCCESS: (state, { payload: { data } }) => ({
      ...state,
      isPending: false,
      ...data
    }),
    FAILURE: state => ({
      ...state,
      isPending: false,
      isError: true
    })
  }
}, initialValue)

请注意,SUCCESS 和 FAILURE 部分现在位于 [SET_DATA] 内


推荐阅读