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 />
  },
  // 404路由配置
  {
    path: '*',
    element: <NotFound />
  }
])
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

7,嵌套路由

// 使用children属性配置嵌套关系
{
	path: '/',
	element: <Layout />,
	children: [
		{
			// path: '',
			index: true,// index设置为true 默认展示这个二级路由
			element: <Lxx />
		},
	]
}
// 使用<Outlet />组件配置二级路由渲染位置
const Layout = () => {
	return (
		<div>
			<Link to="page1">page1</Link>
			<Link to="page2">page2</Link>
			{/*二级路由出口*/}
			<Outlet />
		</div>
	)
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部