react-router-dom 快速上手
一、概念
路由和组件的对应关系,使页面在同一个 html 快速切换。
二、快速开始
createBrowserRouter 创建路由实例
RouterProvider 组件渲染
// route.tsx
import { createBrowserRouter } from 'react-router-dom';
import Home from "./views/Home"
import Login from "./views/Login"
const router = createBrowserRouter({
path: "/",
element: <Home />,
},
{
path: '/login',
element: <Login />
});
export default router;
// main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider } from "react-router-dom";
import router from "./router";
ReactDom.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
三、路由模式
history 模式:createBrowserRouter
hash 模式:createHashRouter
四、路由跳转
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/home", { replace: true });
五、路由传参
1. searchParams 方式
// 设置
navigate("/home?id=1");
// 获取
import { useSearchParams } from "react-router-dom";
const [params] = useSearchParams();
params.get("id");
// 多个参数
navigate("/home?id=1&name=yq");
2. params 方式
// 设置
router = {
path: "/home/:id",
};
navigate("/home/1");
// 获取
import { useParams } from "react-router-dom";
const { id } = useParams();
六、嵌套路由
const router = createBrowserRouter([
{
path: "/",
element: <Layout></Layout>,
children: [
{
path: "/user",
element: <User></User>,
},
],
},
]);
export default (
<div>
<Outlet></Outlet>
</div>
);
七、默认二级路由
createBrowserRouter([
{
path: "/",
element: <Layout></Layout>,
children: [
{
index: true,
element: <User></User>,
},
],
},
]);
八、404 路由
createBrowserRouter([
{
path: "*",
elemetn: <NotFound></NotFound>,
},
]);