反应路由器V6如何在AXIOS拦截器中使用‘Navigate`重定向 [英] React router v6 how to use `navigate` redirection in axios interceptor

查看:11
本文介绍了反应路由器V6如何在AXIOS拦截器中使用‘Navigate`重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import axios from "axios";
import { useNavigate } from "react-router-dom";

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {

          // Won't work
          useNavigate()("/login");

        }
      }
    }

    return Promise.reject(er);
  }
);

推荐答案

在RRDv6之前的世界中,您将创建一个自定义的history对象,将其导出、导入并传递给Router,然后导入并在外部脚本逻辑(如redux-thunks、axios实用程序等)中访问。

若要在RRDv6中复制,还需要创建自定义路由器组件,以便可以向其传递外部history对象。这是因为所有较高级别的RRDv6路由器都维护自己的内部历史上下文,因此我们需要复制历史实例化和状态部分,并传入道具以适应基本Router组件的新API。

import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};

创建所需的历史记录对象:

import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;

导入并传递到新的CustomRouter

import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>

在AXIOS函数中导入和使用:

import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);

这篇关于反应路由器V6如何在AXIOS拦截器中使用‘Navigate`重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆