我的react-router-dom
版本是6.16.0
。之前在react
中是这样配置路由的
App.jsx
javascript
import ReactDOM from 'react-dom/client';
import { HashRouter, Route, Routes } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById("app"));
root.render(
<HashRouter>
<Routes>
<Route
path={XXX}
element={<Component></Component>}
key={XXX} />
</Routes>
</HashRouter>
);
然后使用axios
做接口拦截,当接口的是响应码是10000
的时候,跳转到登录页面(10000
表示接口返回token过期),但是像上面这样使用路由,该怎么在组件外面(例如axios
的逻辑中)做路由跳转呢。
目前看这种方法好像无法做跳转。
可以使用下面的方式做
router/index.jsx
javascript
import { createHashRouter } from "react-router-dom";
export const router = createHashRouter([
{
path: "/",
element: <Component />,
},
]);
App.jsx
javascript
import React, { useEffect } from "react";
import { RouterProvider, createHashRouter } from "react-router-dom";
import { router } from "@/router";
export default () => {
return (
<RouterProvider router={router} />
);
};
然后如果组件外面想切换路由:
就类似这样:
javascript
import { router } from "@/router";
router.navigate('/login');