redux - 在 axios 拦截器中调度其他操作时忽略 Redux 操作负载
问题描述
我需要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)
解决方案
减速机是完全错误的。它应该是:
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] 内
推荐阅读
- angular - 如何将服务器端打字稿文件添加到 Angular 7 项目并自动构建?
- solr - 找不到类“tx_solr_indexqueue_PageIndexer”
- python - 只能将部分数据插入到csv中
- php - 我如何将( id ) url 插入数据库 Laravel
- python-2.7 - Numpy 和逆矩阵 - 只做一个重塑指令的方法
- python - 如何卸载 TensorFlow 2.0.0-alpha0?
- c# - 如何在 PHP 中使用字典类型数组
- c# - 如何使用 .net 内核发布数据并从 Unix 套接字获取响应
- ios - 5分钟后如何在后台调用api?
- python - 如何将 Django TimeField 更改为 24 小时格式