安装
npm i react-router-dom
引入
import {Route,createBrowserRouter,createRoutesFromElements,RouterProvider} from 'react-router-dom'
在app.jsx
const router = createBrowserRouter(createRoutesFromElements(<Route index element = {<h1>My App</h1>}/>)
)const App = () => {return <RouterProvider router={router}/>
}
使用object写路由
const router = createBrowserRouter([{path:"/",element:(<h2>hello rainbow</h2>)},{path:"about",element:<h2>little puppy</h2>}
])
或直接使用<Route/>组件写路由
const router = createBrowserRouter(createRoutesFromElements(<Route path='/' element={<h2>hello rainbow</h2>}></Route>
))
路由嵌套
const router = createBrowserRouter(createRoutesFromElements(<Route path='/' element={<MainLayout/>}><Route path="contact" element = {<h5 >some peopel just bad</h5>}/></Route>
))
别忘了放子路由出口
在父 route 元素中使用outlet来渲染其子 route 元素。这允许在渲染子路由时显示嵌套 UI。
动态传参
{/* :id 表示id是动态的 */}<Route path='/job/:id' element={<JobPage/>}/>
- Link跳转
1.引入
import { Link } from 'react-router-dom'
2.使用
<a
href="/jobs"className="text-white hover:bg-gray-900 hover:text-white rounded-md px-3 py-2"
>Jobs</a> <Link
to="/index"
className="text-white bg-black hover:bg-gray-900 hover:text-white rounded-md px-3 py-2">Home</Link>
原有的a标签 href跳转可以改成Link 的 to,浏览器不会刷新一次再加载
3.active link
- NotFoundPages
<Route path='/' element={<MainLayout />}><Route index element={<HomePage />} /><Route path='/jobs' element={<JobsPage/>}/>{/* 包罗万象 */}<Route path='*' element={<NotFoundPages/>}/></Route>
import { Link } from "react-router-dom"
import { FaExclamationTriangle } from "react-icons/fa"
const NotFoundPages = () => {return (<section className="text-center flex flex-col justify-center items-center h-96"><FaExclamationTriangle className="fas fa-exclamation-triangle text-yellow-400 fa-4x mb-4"/><h1 className="text-6xl font-bold mb-4">404 Not Found</h1><p className="text-xl mb-5">This page does not exist</p><Linkto="/"className="text-white bg-indigo-700 hover:bg-indigo-900 rounded-md px-3 py-2 mt-4">Go Back</Link></section>)
}export default NotFoundPages
4.获得路由中带的参数
import { useParams } from "react-router-dom";
const {id} = useParams();
5.loader
每个路由都可以定义一个 “loader” 函数,以便在路由元素呈现之前向路由元素提供数据。
定义loader
import { useParams,useLoaderData } from "react-router-dom";const jobLoader = async ({params}) => {const res = await fetch(`/api/jobs/${params.id}`)const data = await res.json()return data
}
在路由种使用loader
<Route path='/jobs/:id' element={<JobPage/>} loader={jobLoader}/>
6.useNavigate