【发布时间】:2020-12-17 12:51:35
【问题描述】:
我正在寻找的是一种处理 API 错误代码的通用方法。例如:
- 如果有
error.status.code401(in this case the 401 would be unauthorized)。 我想调度某个动作,例如清理 redux 状态,并且用户必须再次登录。 - 如果有
error.status.code404(not found)。我想将用户重定向或推送到某个路线。
这些动作对于每个动作都是相同的行为。
以下函数的问题是它没有可用的调度。我正在寻找一种在 redux 中间件中实现这种行为的方法。老实说,没有太多关于它的信息。
** 我的 API 函数:**
export const fetchApi = (url, config) => {
return fetch(url, config)
.then((res) => {
if (!res.ok) {
if (res.statusCode === 401) {
// dispatch an action, not possible dispatch is not avaible
}
}
if (res.ok) {
return res.text();
}
})
.then((text) => (text.length ? JSON.parse(text) : {}));
};
我正在寻找这个方向:
store.js
import {
createStore,
applyMiddleware,
compose,
} from 'redux';
import thunkMiddleware from 'redux-thunk';
import { persistStore } from 'redux-persist';
import { persistedReducer } from './config';
export default () => {
const middleware = [thunkMiddleware];
const middleWareEnhancer = applyMiddleware(
...middleware,
thunk.withExtraArgument({
apiFetch: (...args) =>
fetchApi(...args).catch((err) => {
// general error handling when fetchApi has certain errors
// that needs to change something in redux store
if (err.statusCode === 401) {
//dispatch clean all data action
store.dispatch({ type: 'reset' });
//location.href redirect or reload
}
// reject the promise
return Promise.reject(err);
}),
})
);
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
persistedReducer,
composeEnhancers(middleWareEnhancer)
);
let persistor = persistStore(store);
return { store, persistor };
};
我只是盲目地寻找可能的解决方案。如果您有任何建议,请随时发表评论。
更新: 当我添加这个中间件时。我可以从动作中收听有效载荷,看看是否有人抛出“未经授权”。基于此,我可以调度一个动作。我不知道这个解决方案有多防水。
更新:
中间件:
const authInterceptor = ({ dispatch }) => (next) => (
action
) => {
if (action.payload === 'unauthorized') {
dispatch(something());
} else {
next(action);
}
};
Store.js
export default () => {
const middleware = [thunkMiddleware, authInterceptor];
const middleWareEnhancer = applyMiddleware(...middleware);
const composeEnhancers =
(true && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
compose;
let store = createStore(
persistedReducer,
composeEnhancers(middleWareEnhancer)
);
let persistor = persistStore(store);
return { store, persistor };
};
【问题讨论】:
标签: reactjs api redux middleware http-status-code-401