react-router-dom6文档 https://reactrouter.com/en/main

image.png

react-router-dom v6新特性

  1. 重命名为
  2. 的新特性变更
  3. 嵌套路由变得更简单
  4. element 代替 component,render函数
  5. 用 useNavigate代替 useHistory
  6. 新钩子 useRoutes代替 react-router-config
  7. 打包体积减少:从20kb到8kb
  8. 删除 Prompt,usePrompt, useBlock
  9. 父路由渲染子路由, 代替 rops.children
  10. 组件 props 里能拿到的 location、history、match 等信息,现在可通过 useRouteData() 获取,好处:减少了 props 的传递

react-router-dom API

BrowserRouter,基于 history.pushState,history.replaceState,需要服务端配置
HashRouter,先拼接 /#,再拼接路径,基于 location.hash, location.replace

  1. const keys = [
  2. "BrowserRouter",
  3. "HashRouter", /#
  4. "Link", a 链接
  5. "MemoryRouter",
  6. "NavLink",
  7. "Navigate",
  8. "NavigationType",
  9. "Outlet",
  10. "Route",
  11. "Router",
  12. "Routes",
  13. "UNSAFE_LocationContext",
  14. "UNSAFE_NavigationContext",
  15. "UNSAFE_RouteContext",
  16. "createPath",
  17. "createRoutesFromChildren",
  18. "createSearchParams",
  19. "generatePath",
  20. "matchPath",
  21. "matchRoutes",
  22. "parsePath",
  23. "renderMatches",
  24. "resolvePath",
  25. "unstable_HistoryRouter",
  26. "useHref",
  27. "useInRouterContext",
  28. "useLinkClickHandler",
  29. "useLocation",
  30. "useMatch",
  31. "useNavigate",
  32. "useNavigationType",
  33. "useOutlet",
  34. "useOutletContext",
  35. "useParams",
  36. "useResolvedPath",
  37. "useRoutes",
  38. "useSearchParams"
  39. ]

react-router-dom

  1. import {
  2. createBrowserRouter,
  3. RouterProvider,
  4. } from "react-router-dom"
  5. import routes from './routes'
  6. const router = createBrowserRouter(routes, {
  7. // basename: pkg.name,
  8. // basename?: string;
  9. // hydrationData?: HydrationState;
  10. // window?: Window;
  11. });
  12. function RouterConfig() {
  13. return (
  14. <ConfigProvider locale={locale}>
  15. <RouterProvider
  16. router={router}
  17. // fallbackElement?: React.ReactNode;
  18. />
  19. </ConfigProvider>
  20. )
  21. }
  22. export default RouterConfig

Routes 代替 Switch

Routes代替 Switch,其他功能都一样

  1. import List from './List';
  2. <Routes>
  3. <Route path='/' element={<Home />} />
  4. <Route path='/list' element={<List />} />
  5. </Routes>
  6. // v5
  7. <Switch>
  8. <Route path='/' element={<Home />} />
  9. <Route path='/list' element={<List />} />
  10. </Switch>