【问题标题】:Redirect in react redux-tool-kit fetchBase query interceptor在 react redux-toolkit fetchBasequery 拦截器中重定向
【发布时间】:2021-12-17 12:23:06
【问题描述】:

我有一个 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;

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

【问题讨论】:

    标签: reactjs react-redux fetch react-router-dom redux-toolkit


    【解决方案1】:

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

    此外,您不需要中间件,您可能会更好地使用wrapping your baseQuery

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2018-11-27
      • 1970-01-01
      • 2015-08-22
      • 2018-12-25
      • 2021-12-25
      • 2014-12-23
      • 2013-03-11
      • 2017-08-29
      相关资源
      最近更新 更多