reactjs - react redux-tool-kit fetchBase 查询拦截器中的重定向
问题描述
我有一个 react/redux 应用程序,我正在使用 redux-tool-kit fetchBasequery,并且我正在使用自定义 authInterceptor 中间件,我在其中进行了错误处理。在 authInterceptor 中,如果出现 401 错误,我会尝试重定向到登录页面。我正在使用 useNavigate 进行重定向,但出现错误“错误:无效的挂钩调用。挂钩只能在函数组件的主体内部调用。”
//authInterceptor.ts
import { isRejectedWithValue, Middleware } from '@reduxjs/toolkit';
import navigate from '../utils';
const authInterceptor: Middleware = () => (next) => (action) => {
if (isRejectedWithValue(action) && action.payload.status === 401) {
console.log('401 error');
navigate('/login');
}
return next(action);
};
export default authInterceptor;
//utils.ts
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
export default navigate;
有没有更好的方法来做到这一点或我如何处理重定向
解决方案
您可能必须将history
您创建的对象与您的Router
设置一起使用,然后在history.push
那里执行。
此外,您不需要中间件,您可能会更好地包装您的 baseQuery
推荐阅读
- python - python Django中存储的索引文件示例在哪里?
- javascript - 单击按钮时如何将url放入变量中
- vue.js - Vue $emit 没有在 finally() 中执行
- javascript - JavaScript - 如何从另一个函数访问变量?
- r - 代表错误:尝试复制“闭包”类型的对象(if 语句中的箱线图)
- android - Android ConstraintLayout内的按钮拒绝显示以水平方向居中的多字符文本
- security - 路径攻击的用户名和密码应该是什么
- c# - C# - 在一个方法中,我怎样才能有 2 个参数是一个?
- sql - 具有各自值的多列到行
- kubernetes - 如何在helm中设置环境变量?