1, 安装路由
npm i react-router-dom
2,路由组件 createBrowserRouter
// router/index.js
import { createBrowserRouter } from "react-router-dom"import Home from '../page/home'
import New from '../page/new'const router = createBrowserRouter([{path: '/',element: <Home />},{path: '/new',element: <New />}
])
export default router
3,使用路由
//index.js
import router from './router'
import { RouterProvider } from 'react-router-dom'root.render(// <React.StrictMode><RouterProvider router={router}></RouterProvider>// </React.StrictMode>
)
4,声明式导航
import { Link } from "react-router-dom"
<Link to='/new'>new</Link>
5,编程式导航
import { useNavigate } from "react-router-dom"
// 执行navigate
const navigate = useNavigate()// 使用
<span onClick={() => navigate('/')}>跳转到首页</span>
6,传参
// ====SearchParams======
<span onClick={() => navigate('/home?id=100&name=json')}>跳转到首页</span>
import { useSearchParams } from "react-router-dom"
const [params] = useSearchParams()
const id = params.get('id')
// ====params======
path: '/new/:id',// 路由添加占位符
<span onClick={() => navigate('/new/1000')}>跳转到首页</span>
import { useParams } from "react-router-dom"
const params = useParams ()
const id = params.id