react-router-dom6文档 https://reactrouter.com/en/main
- v6 https://reactrouter.com/docs/en/v6/getting-started/tutorial
- v5 https://v5.reactrouter.com/web/guides/quick-start
react-router-dom v6新特性
重命名为 的新特性变更 - 嵌套路由变得更简单
- element 代替 component,render函数
- 用 useNavigate代替 useHistory
- 新钩子 useRoutes代替 react-router-config
- 打包体积减少:从20kb到8kb
- 删除 Prompt,usePrompt, useBlock
- 父路由渲染子路由,
代替 rops.children - 组件 props 里能拿到的 location、history、match 等信息,现在可通过 useRouteData() 获取,好处:减少了 props 的传递
react-router-dom API
BrowserRouter,基于 history.pushState,history.replaceState,需要服务端配置
HashRouter,先拼接 /#,再拼接路径,基于 location.hash, location.replace
const keys = [
"BrowserRouter",
"HashRouter", /#
"Link", a 链接
"MemoryRouter",
"NavLink",
"Navigate",
"NavigationType",
"Outlet",
"Route",
"Router",
"Routes",
"UNSAFE_LocationContext",
"UNSAFE_NavigationContext",
"UNSAFE_RouteContext",
"createPath",
"createRoutesFromChildren",
"createSearchParams",
"generatePath",
"matchPath",
"matchRoutes",
"parsePath",
"renderMatches",
"resolvePath",
"unstable_HistoryRouter",
"useHref",
"useInRouterContext",
"useLinkClickHandler",
"useLocation",
"useMatch",
"useNavigate",
"useNavigationType",
"useOutlet",
"useOutletContext",
"useParams",
"useResolvedPath",
"useRoutes",
"useSearchParams"
]
react-router-dom
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom"
import routes from './routes'
const router = createBrowserRouter(routes, {
// basename: pkg.name,
// basename?: string;
// hydrationData?: HydrationState;
// window?: Window;
});
function RouterConfig() {
return (
<ConfigProvider locale={locale}>
<RouterProvider
router={router}
// fallbackElement?: React.ReactNode;
/>
</ConfigProvider>
)
}
export default RouterConfig
Routes 代替 Switch
Routes代替 Switch,其他功能都一样
import List from './List';
<Routes>
<Route path='/' element={<Home />} />
<Route path='/list' element={<List />} />
</Routes>
// v5
<Switch>
<Route path='/' element={<Home />} />
<Route path='/list' element={<List />} />
</Switch>