在 axios 拦截器中调度其他动作时,Redux 动作负载被忽略

Redux action payload being ignored when dispatching some other action inside 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 上进行一些 'heavy' 计算(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)的 reducer 被调用时,它甚至看不到有效负载。

这是一个动作示例:

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)

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

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]