React-Router v6新特性解讀及遷移指南
前言
18 年初,React Router的主要開發(fā)人員創(chuàng)建一個(gè)名為Reach Router的輕量級替代方案。
原來是相互抗衡的,卻沒想React Router直接拿來合并(真香!)
目前 v6已是測試最后一版,估計(jì)新的特性不出意外就是下面這些了:
- <Switch>重命名為<Routes>。
- <Route>的新特性變更。
- 嵌套路由變得更簡單。
- 用useNavigate代替useHistory。
- 新鉤子useRoutes代替react-router-config。
- 大小減少:從20kb到8kb
1. <Switch>重命名為<Routes>
該頂級組件將被重命名。但是,其功能大部分保持不變(嗨,瞎折騰)。
- // v5
- <Switch>
- <Route exact path="/"><Home /></Route>
- <Route path="/profile"><Profile /></Route>
- </Switch>
- // v6
- <Routes>
- <Route path="/" element={<Home />} />
- <Route path="profile/*" element={<Profile />} />
- </Routes>
2. <Route>的新特性變更
component/render被element替代
總而言之,簡而言之。就是變得更好用了。
- import Profile from './Profile';
- // v5
- <Route path=":userId" component={Profile} />
- <Route
- path=":userId"
- render={routeProps => (
- <Profile routeProps={routeProps} animate={true} />
- )}
- />
- // v6
- <Route path=":userId" element={<Profile />} />
- <Route path=":userId" element={<Profile animate={true} />} />
3. 嵌套路由變得更簡單
具體變化有以下:
- <Route children> 已更改為接受子路由。
- 比<Route exact>和<Route strict>更簡單的匹配規(guī)則。
- <Route path> 路徑層次更清晰。
3.1 簡化嵌套路由定義
v5中的嵌套路由必須非常明確定義,且要求在這些組件中包含許多字符串匹配邏輯(活久見啊,終于意識到這個(gè)問題了。)
且看之前的處理:
- // v5
- import {
- BrowserRouter,
- Switch,
- Route,
- Link,
- useRouteMatch
- } from 'react-router-dom';
- function App() {
- return (
- <BrowserRouter>
- <Switch>
- <Route exact path="/" component={Home} />
- <Route path="/profile" component={Profile} />
- </Switch>
- </BrowserRouter>
- );
- }
- function Profile() {
- let { path, url } = useRouteMatch();
- return (
- <div>
- <nav>
- <Link to={`${url}/me`}>My Profile</Link>
- </nav>
- <Switch>
- <Route path={`${path}/me`}>
- <MyProfile />
- </Route>
- <Route path={`${path}/:id`}>
- <OthersProfile />
- </Route>
- </Switch>
- </div>
- );
- }
而在v6中,你可以刪除字符串匹配邏輯。不需要任何useRouteMatch()!
- // v6
- import {
- BrowserRouter,
- Routes,
- Route,
- Link,
- Outlet
- } from 'react-router-dom';
- function App() {
- return (
- <BrowserRouter>
- <Routes>
- <Route path="/" element={<Home />} />
- <Route path="profile/*" element={<Profile/>} />
- </Routes>
- </BrowserRouter>
- );
- }
- function Profile() {
- return (
- <div>
- <nav>
- <Link to="me">My Profile</Link>
- </nav>
- <Routes>
- <Route path="me" element={<MyProfile />} />
- <Route path=":id" element={<OthersProfile />} />
- </Routes>
- </div>
- );
- }
當(dāng)然,還有更酸爽的操作,直接在路由里定義<Route>的<Route>,然后用接下來的一個(gè)新API:Outlet
3.2 新API:Outlet
這玩意兒,像極了{(lán)this.props.children},具體用法看以下例子:
- function App() {
- return (
- <BrowserRouter>
- <Routes>
- <Route path="/" element={<Home />} />
- <Route path="profile" element={<Profile />}>
- <Route path=":id" element={<MyProfile />} />
- <Route path="me" element={<OthersProfile />} />
- </Route>
- </Routes>
- </BrowserRouter>
- );
- }
- function Profile() {
- return (
- <div>
- <nav>
- <Link to="me">My Profile</Link>
- </nav>
- {/*
- 將直接根據(jù)上面定義的不同路由參數(shù),渲染<MyProfile />或<OthersProfile />
- */}
- <Outlet />
- </div>
- )
- }
3.3 多個(gè)<Routes />
以前,我們只能 在React App中使用一個(gè) Routes。但是現(xiàn)在我們可以在React App中使用多個(gè)路由,這將幫助我們基于不同的路由管理多個(gè)應(yīng)用程序邏輯。
- import React from 'react';
- import { Routes, Route } from 'react-router-dom';
- function Dashboard() {
- return (
- <div>
- <p>Look, more routes!</p>
- <Routes>
- <Route path="/" element={<DashboardGraphs />} />
- <Route path="invoices" element={<InvoiceList />} />
- </Routes>
- </div>
- );
- }
- function App() {
- return (
- <Routes>
- <Route path="/" element={<Home />} />
- <Route path="dashboard/*" element={<Dashboard />} />
- </Routes>
- );
- }
4. 用useNavigate代替useHistory
從一目了然改到雙目失明。。。
總感覺React Router團(tuán)隊(duì)有點(diǎn)兒戲。。。
- // v5
- import { useHistory } from 'react-router-dom';
- function MyButton() {
- let history = useHistory();
- function handleClick() {
- history.push('/home');
- };
- return <button onClick={handleClick}>Submit</button>;
- };
現(xiàn)在,history.push()將替換為navigation():
- // v6
- import { useNavigate } from 'react-router-dom';
- function MyButton() {
- let navigate = useNavigate();
- function handleClick() {
- navigate('/home');
- };
- return <button onClick={handleClick}>Submit</button>;
- };
history的用法也將被替換成:
- // v5
- history.push('/home');
- history.replace('/home');
- // v6
- navigate('/home');
- navigate('/home', {replace: true});
強(qiáng)行達(dá)成共識
5. 新鉤子useRoutes代替react-router-config。
感覺又是一波強(qiáng)行hooks,但還是相對于之前簡潔了一些。。。
- function App() {
- let element = useRoutes([
- { path: '/', element: <Home /> },
- { path: 'dashboard', element: <Dashboard /> },
- { path: 'invoices',
- element: <Invoices />,
- children: [
- { path: ':id', element: <Invoice /> },
- { path: 'sent', element: <SentInvoices /> }
- ]
- },
- // 重定向
- { path: 'home', redirectTo: '/' },
- // 404找不到
- { path: '*', element: <NotFound /> }
- ]);
- return element;
- }
6. 大小減少:從20kb到8kb
React Router v6給我們帶來方便的同時(shí),還把包減少了一半以上的體積。。。
感覺可以去看一波源碼了。。。
7. 遷移及其它重要修復(fù)...
官方的遷移指南在這里:React Router v6 遷移指南
其實(shí)上面所列的新特性,基本就是遷移的全部內(nèi)容了。
基礎(chǔ)的起手式就是更新包:
- $ npm install react-router@6 react-router-dom@6
- # or, for a React Native app
- $ npm install react-router@6 react-router-native@6
其中我覺得特別需要注意的一點(diǎn)是:React Router v6 使用簡化的路徑格,僅支持 2 種占位符:動(dòng)態(tài):id樣式參數(shù)和*通配符
以下都是 v6 中的有效路由路徑:
- /groups
- /groups/admin
- /users/:id
- /users/:id/messages
- /files/*
- /files/:id/*
- /files-*
使用RegExp正則匹配的路徑將無效:
- /users/:id?
- /tweets/:id(\d+)
- /files/*/cat.jpg
v6中的所有路徑匹配都將忽略 URL 上的尾部"/"。實(shí)際上,<Route strict>已被刪除并且在 v6 中無效。這并不意味著您不需要使用斜杠。
在v5版本之前的路徑,存在路由歧義
- 當(dāng)前路徑:"/users",則<Link to="me">將跳轉(zhuǎn)<a href="/me">。
- 當(dāng)前路徑:"/users/",則<Link to="me">將跳轉(zhuǎn)<a href="/users/me">。
React Router v6修復(fù)了這種歧義,取消了尾部"/":
- 當(dāng)前路徑:"/users",則<Link to="me">將跳轉(zhuǎn)<a href="/users/me">。
- 當(dāng)前路徑:"/users",則<Link to="../me">將跳轉(zhuǎn)<a href="/me">。
其形式更像命令行cd的用法:
- // 當(dāng)前路徑為 /app/dashboard
- <Link to="stats"> // <a href="/app/dashboard/stats">
- <Link to="../stats"> // <a href="/app/stats">
- <Link to="../../stats"> // <a href="/stats">
- <Link to="../../../stats"> // <a href="/stats">
- // 命令行當(dāng)前路徑為 /app/dashboard
- cd stats // pwd is /app/dashboard/stats
- cd ../stats // pwd is /app/stats
- cd ../../stats // pwd is /stats
- cd ../../../stats // pwd is /stats