在axios拦截器内分派其他动作时,将忽略Redux动作有效负载

时间:2020-01-28 13:42:11

标签: redux axios interceptor

我需要在进行任何其他操作之前先致电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
      }
    }
  }
)

intro是一个重新选择选择器,用于对serverTime进行一些“大量”计算(serverTime是checkConnection的结果)

checkConnection是一个重做的重击操作:

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)

1 个答案:

答案 0 :(得分:0)

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

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)

请注意,成功和失败部分现在位于[SET_DATA]