1.配置 basename
方式一
1.创建一个router/index.tsx 文件
import { createBrowserRouter } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Login from "../pages/login";
const basename = process.env.REACT_APP_ROUTERBASE || "";
const router = createBrowserRouter([
{
path: `${basename}/`,
element: <Home />,
},
{
path: `${basename}/login`,
element: <Login />,
},
{
path: `${basename}/about`,
element: <About />,
},
]);
export default router;
2.在app.tsx 配置
import { Provider } from "react-redux";
import store from "./store";
import { RouterProvider } from "react-router-dom";
import router from "./router";
function App() {
return (
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
);
}
export default App;
方式二
1.创建一个router/index.tsx 文件
import { createBrowserRouter, Routes, Route } from "react-router-dom";
import Home from "../pages/Home";
import About from "../pages/About";
import Login from "../pages/login";
const routes = [
{
path: `/`,
element: <Home />,
},
{
path: `/login`,
element: <Login />,
},
{
path: `/about`,
element: <About />,
},
];
export default function Router() {
return (
<Routes>
{routes.map((route, index) => (
<Route key={index} path={route.path} element={route.element} />
))}
</Routes>
);
}
2.在app.tsx 配置
import { Provider } from "react-redux";
import store from "./store";
import { RouterProvider, BrowserRouter } from "react-router-dom";
import Router from "./router";
function App() {
return (
<Provider store={store}>
<BrowserRouter basename="/app">
<Router></Router>
</BrowserRouter>
</Provider>
);
}
export default App;
2.BrowserRouter
和HashRouter
的使用示例
// 使用 BrowserRouter
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import LoginPage from './LoginPage';
import HomePage from './HomePage';
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<HomePage />} />
</Routes>
</BrowserRouter>
);
};
export default App;
// 使用 HashRouter
import React from 'react';
import { HashRouter, Routes, Route } from 'react-router-dom';
import LoginPage from './LoginPage';
import HomePage from './HomePage';
const App = () => {
return (
<HashRouter>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/" element={<HomePage />} />
</Routes>
</HashRouter>
);
};
export default App;
在这两个示例中,BrowserRouter
和HashRouter
分别作为根组件包裹了路由配置。它们的工作方式基本相同,只是BrowserRouter
使用HTML5的history API来管理路由,而HashRouter
使用URL中的哈希部分来管理路由。选择使用哪种方式取决于你的项目需求和部署环境。
3.编程式导航
import React from 'react';
import { useNavigate } from 'react-router-dom';
const LoginPage = () => {
const navigate = useNavigate();
const handleLogin = () => {
// 执行登录逻辑
// 登录成功后进行页面导航
navigate('/'); // 导航到首页
};
return (
<div>
<h2>Login Page</h2>
<button onClick={handleLogin}>Login</button>
</div>
);
};
export default LoginPage;
注: 如果在跳转时想要替换记录,可以添加额外参数 replace 为 true
navigate('/', { replace: true })