首页 > 解决方案 > 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;

有没有更好的方法来做到这一点或我如何处理重定向

标签: reactjsreact-reduxfetchreact-router-domredux-toolkit

解决方案


您可能必须将history您创建的对象与您的Router设置一起使用,然后在history.push那里执行。

此外,您不需要中间件,您可能会更好地包装您的 baseQuery


推荐阅读