在axios拦截器内调度其他操作时忽略Redux操作负载
我需要在执行任何其他操作之前调用在axios拦截器内调度其他操作时忽略Redux操作负载,redux,axios,interceptor,Redux,Axios,Interceptor,我需要在执行任何其他操作之前调用checkConnection,因此我考虑使用axios拦截器: axios.interceptors.request.use( async config => { await store.dispatch(checkConnection()) const { requestTime, hash } = intro(store.getState()) return { ...config, header
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)
减速器完全错了。应该是:
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]内