初始化项目
npx create-react-app react-router-demo --template typescript
首先安装 react-router-dom
{
"react-router-dom": "6.15.0"
}
首先我们记住一点,其实在 react-router 底层,实现了不同宿主的路由,react-router-dom 是针对浏览器的,还有 react-router-native 是针对 react-native 的,这个思路非常值得我们学习,上层抽象,具体宿主环境实现
常见的几种router
createBrowserRouter:浏览器提供的历史管理 常用
createHashRouter: 基于hash 的路由管理,#hello 但是通常#又可以作为锚链接
createMemoryRouter : 内存型路由,路由的管理存储在内存中
createStaticRouter SSR 服务端的
import { Link, Outlet, createBrowserRouter } from "react-router-dom"; import App from './App'; import Home from './home' function Teacher(){ return <div>hello Teacher ! <ul> {[1,4,5].map((item)=>( <li key={item}> <Link key={item} to={`${item}`}>{item}</Link> </li> ))} </ul> <Outlet/></div> } function Student(){ return <div>hello Student ! <Link to="..">返回</Link> </div> } const router = createBrowserRouter([ { path: "/", element: <App/>, },{ path:"/home", element: <Home/> }, { path:"/teacher", element: <Teacher/>, children:[{ path:":id", element:<Student/> }] } ],{ initialEntries: ["/", "/events/123"], initialIndex: 1, }); export default router
createBrowserRouter: http://localhost:3001/teacher
createHashRouter http://localhost:3001/#/teacher
createMemoryRouter http://localhost:3001 路由跳转url 不变
useMatches 获取路由传递的参数 createBrowserRouter 中使用
useMatch 组件中设置匹配的路由
const match = useMatch({path:"/teacher/:id"}) 搭配 createMemoryRouter
const navigate = useNavigate() navigate("/") 路由跳转推荐使用Link ,通过onClick 必须通过鼠标点击才能跳转,link 按住 ctrl + 鼠标左键即可 navigator不行
react-router 源码解析
history : pushstate(浏览器url 记录浏览记录,可回退进一步) replacestate(开启一个全新的页面,不存在回退进一步)
history
-
历史操作,history.pushState、history.replaceState。不会触发 popState
-
监听变更,window.addEventListener("popstate", () => {})
-
操作,history.back(),history.forward(),history.go(),会触发 popState
浏览器路由实现:
history 是指整个浏览器路由历史记录大对象,其中包含长度等属性。
location 是单一页面所对应的资源定位对象,我们可以理解为当页面跳转时,生成location,然后将location push 到history
对于历史记录的监听 Hash hashchange history :popstate
pushState 和 replaceState 可改变页面内容 触发popstate 监听
vue-router双路由框架存储在 github.com/LiangHaley/…