【问题标题】:Redux action payload being ignored when dispatching some other action inside axios interceptor在 axios 拦截器中调度其他操作时忽略 Redux 操作负载
【发布时间】:2020-05-13 22:48:21
【问题描述】:

我需要在任何其他操作之前调用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 是一个 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)

【问题讨论】:

    标签: redux axios interceptor


    【解决方案1】:

    reducer 完全错误。应该是:

    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] 中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 2021-06-30
      • 2017-05-22
      相关资源
      最近更新 更多