【发布时间】: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