reactjs - Redux 中间件中的 ReactJS 处理 API 错误
问题描述
我正在寻找的是一种处理 API 错误代码的通用方法。例如:
- 如果有一个
error.status.code
401
(in this case the 401 would be unauthorized)
. 我想调度某个动作,例如清理 redux 状态并且用户必须再次登录。 - 如果有一个
error.status.code
404
(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 };
};
解决方案
有趣的是,您的问题似乎与 redux-thunk、redux 架构有关。看看处理 redux 我们有三个主要文件,我们应该创建 action 文件,reducers 文件,最后是 store(有些人可能直接将 store 写在根文件中,如 App.js 或 index.js)任何 redux -thunk 逻辑必须存在于操作文件中,这样您就可以将 git 调度作为传递给您的操作的道具 这里是一个示例,如果我们有一个名为 signupUserAsync 的操作来注册我们的用户
const signupUserAsync = (props) => {
return (dispatch ) => {
Api.post(/*whaterever is our URL, pramas, data*/).then(res=> dispatch(saveDataAction(res.data))
}
}
有了它,它就会为你工作。您可以通过此处的文档了解更多信息:https ://github.com/reduxjs/redux-thunk
或者在这种情况下,你可以试试这个 -->
export const fetchApi = (url, config) => {
return (dispatch) => {
fetch(url, config)
.then((res) => {
if (!res.ok) {
if (res.statusCode === 401) {
// Now hopefully you will have the dispatch function working
}
}
if (res.ok) {
return res.text();
}
})
.then((text) => (text.length ? JSON.parse(text) : {}));
}
};
推荐阅读
- python - 如何获取深度学习 caffe python 中存在的点的 x,y 坐标
- javascript - 通过 key 在 mongoDB 中获取价值
- java - 是否可以使用并行流来执行这些循环?
- javascript - 如何通过参数添加对象属性?
- python - 使用 OpenCV 和 Python 获取图像中颜色的百分比
- c++ - 在 C++ 中调用类中的运算符函数
- javascript - 如何将字符串中的所有表情符号替换为 unicode JS
- python - 为 subprocess_checkoutput 选择目录
- java - 使用 SimpleListAdaptor 中的键获取值
- c# - PCLStorage NuGetPackage 不允许在设备上创建文件夹或文件