【react】React Router基础知识
1. 基础用法
npm i react-router-dom
通过浏览器地址栏的切换,可以实现不同组件之间的切换。
import React from "react";
import ReactDOM from "react-dom/client";
// import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createBrowserRouter,RouterProvider } from "react-router-dom";
// 创建路由
const router = createBrowserRouter([{
path:'/login',
element:<div>我是登录页</div>
},{
path:'/article',
element:<div>我是文章页</div>
}])
// 将App组件渲染到id为root的DOM元素中
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
);
reportWebVitals();
进一步将组件单独抽离:
/pages/Article/index.js
const Article = () =>{
return (
<div>我是文章页</div>
)
}
export default Article;
/pages/Login/index.js
import { Link } from "react-router-dom";
const Login = () => {
return (
<div>我是登录页</div>
);
};
export default Login;
/router/index.js
import { createBrowserRouter } from "react-router-dom";
import Login from "../pages/Login";
import Article from "../pages/Article";
const router = createBrowserRouter([
{
path: "/login",
element:<Login/>
},
{
path: "/article",
element: <Article/>
},
]);
export default router;
/index.js
import React from "react";
import ReactDOM from "react-dom/client";
// import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { RouterProvider } from "react-router-dom";
import router from './router/index'
// 将App组件渲染到id为root的DOM元素中
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
2. 路由导航跳转
2.1 声明式导航
声明式导航是指通过在模版中通过<Link/>
组件描述出要跳转到哪里去,比如后台管理系统的左侧菜单通常使用这种方式进行。
通过给组件的to
属性指定要跳转到路由path
,组件会被渲染为浏览器支持的a
链接,如果需要传参直接通过字符串拼接的方式拼接参数。
/pages/Login/index.js
import { Link } from "react-router-dom";
const Login = () => {
return (
<div>
<div>我是登录页</div>
<Link to="/article">去文章页</Link>
</div>
);
};
export default Login;
2.2 编程式导航
编程式导航是指通过useNavigate
钩子得到导航方法,然后通过调用方法以命令式的形式进行路由跳转,比如想在登录请求完毕之后跳转就可以选择这种方式,更加灵活。
通过调用navigate
方法传入地path
实现跳转。
//pages/Login/index.js
import { useNavigate} from "react-router-dom";
const Login = () => {
const navigate = useNavigate()
return (
<div>
<div>我是登录页</div>
<button onClick={() =>navigate('/article')}>去文章页</button>
</div>
);
};
export default Login;
2.3 路由导航传参
searchParams传参
在路径后面拼接?
进行参数传递,多个参数以&
分隔。
//pages/Login/index.js
import { useNavigate} from "react-router-dom";
const Login = () => {
const navigate = useNavigate()
return (
<div>
<div>我是登录页</div>
{/* 路由跳转并传参 */}
<button onClick={() =>navigate('/article?id=1001&name=张三')}>去文章页</button>
</div>
);
};
export default Login;
使用useSearchParams
来获取传递过的的params参数
///pages/Article/index.js
import { useSearchParams } from "react-router-dom";
const Article = () => {
const [params] = useSearchParams();
const id = params.get("id");
const name = params.get("name");
return (
<>
<div>我是文章页</div>
<div>
{id}-{name}
</div>
</>
);
};
export default Article;
params传参
router路径配置时,需要提供传参字段的占位符。
获取路由传参时,使用useParams
拿到传参对象。
//pages/Login/index.js
import { createBrowserRouter } from "react-router-dom";
import Login from "../pages/Login";
import Article from "../pages/Article";
const router = createBrowserRouter([
{
path: "/login",
element:<Login/>
},
{
path: "/article/:id/:name",
element: <Article/>
},
]);
export default router;
//pages/Login/index.js
import { Link ,useNavigate} from "react-router-dom";
const Login = () => {
const navigate = useNavigate()
return (
<div>
<div>我是登录页</div>
{/* 路由跳转并传参 */}
<button onClick={() =>navigate('/article/1001/张三')}>去文章页</button>
</div>
);
};
export default Login;
//pages/Article/index.js
import { useParams } from "react-router-dom";
const Article = () => {
const params = useParams();
const { id, name } = params;
return (
<>
<div>我是文章页</div>
<div>
{id}-{name}
</div>
</>
);
};
export default Article;
2.4 嵌套路由配置
1.使用 children
属性配置路由嵌套关系
2.使用<Outlet/>
组件配置二级路由渲染位置
// router/index.js
import { createBrowserRouter } from "react-router-dom";
import Login from "../pages/Login";
import Article from "../pages/Article";
import Layout from "../pages/Layout";
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
path: "/login",
element: <Login />,
},
{
path: "/article",
element: <Article />,
},
],
},
]);
export default router;
// pages/Layout/index.js
import { Link,Outlet } from "react-router-dom";
const Layout = () => {
return (
<div>
<h1>Layout</h1>
<Link to="/login">登录页面</Link>
<Link to="/article">文章页面</Link>
{/* 配置二级路由的出口 */}
<Outlet/>
</div>
);
};
export default Layout;
设置默认二级路由
设置默认二级路由的index为true,取消path路径设置
// router/index.js
import { createBrowserRouter } from "react-router-dom";
import Login from "../pages/Login";
import Article from "../pages/Article";
import Layout from "../pages/Layout";
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
// 设置默认二级路由
index: true,
element: <Login />,
},
{
path: "/article",
element: <Article />,
},
],
},
]);
export default router;
默认二级路由跳转路径为/
// pages/Layout/index.js
import { Link, Outlet } from "react-router-dom";
const Layout = () => {
return (
<div>
<h1>Layout</h1>
<Link to="/">登录页面</Link>
<Link to="/article">文章页面</Link>
{/* 配置二级路由的出口 */}
<Outlet />
</div>
);
};
export default Layout;
2.5 404路由配置
当浏览器输入url的路径在整个路由配置中都找不到对应的 path,为了用户体验,可以使用 404 兜底组件进行
渲染。
1.准备一个NotFound组件
2.在路由表数组的末尾,以*
号作为路由path配置路由
//router/index.js
import { createBrowserRouter } from "react-router-dom";
import Login from "../pages/Login";
import Article from "../pages/Article";
import Layout from "../pages/Layout";
import NotFound from "../pages/NotFound";
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
// 设置默认二级路由
index: true,
element: <Login />,
},
{
path: "/article",
element: <Article />,
},
],
},{
// 404路由配置
path:'*',
element: <NotFound />
}
]);
export default router;
//pages/NotFound/index.js
const NotFound = () => {
return (
<div>
<h1>404</h1>
<p>页面未找到</p>
</div>
);
};
export default NotFound;
3. ReactRouter两种路由模式
各个主流框架的路由常用的路由模式有两种,history
模式和hash
模式, ReactRouter分别由 createBrowerRouter
和createHashRouter
函数负责创建。