什么是React Router
許多現(xiàn)代網(wǎng)站實際上是由一個頁面組成的嘶是,它們看起來就像多個頁面,因為它們包含呈現(xiàn)為單獨頁面的組件竿奏。 這些通常稱為SPA-單頁應(yīng)用程序荠耽。 從根本上說,React Router的作用是根據(jù)URL中使用的路由(在首頁中為/豺谈,在About頁面中為/ about等)郑象,有條件地渲染某些組件以進行顯示。
例如我們可以通過React Router將 www.myurl.com/ 與 www.myurl.com/about 或者 www.myurl.com/shop 鏈接起來茬末。
那怎么做到這些呢厂榛?先看下React Router的基本組件:
React Router 組件
現(xiàn)在的React Router版本中已不需要路由配置,現(xiàn)在一切皆組件丽惭。
ReactRouter中提供了以下三大組件:
-
Router
是所有路由組件共用的底層接口組件击奶,它是路由規(guī)則制定的最外層的容器。 -
Route
路由規(guī)則匹配吐根,并顯示當(dāng)前的規(guī)則對應(yīng)的組件正歼。 -
Link
路由跳轉(zhuǎn)的組件
當(dāng)然每個組件下又會有幾種不同的子類組件實現(xiàn)。比如: Router組件就針對不同功能和平臺對應(yīng)用:
-
<BrowserRouter>
瀏覽器的路由組件 -
<HashRouter>
URL格式為Hash路由組件 -
<MemoryRouter>
內(nèi)存路由組件 -
<NativeRouter>
Native的路由組件 -
<StaticRouter>
地址不改變的靜態(tài)路由組件
React Router 設(shè)計
- 安裝包
npm install react-router-dom
- 創(chuàng)建router, 參考官方例子
在App.js 中放入以下代碼
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
// This site has 3 pages, all of which are rendered
// dynamically in the browser (not server rendered).
//
// Although the page does not ever refresh, notice how
// React Router keeps the URL up to date as you navigate
// through the site. This preserves the browser history,
// making sure things like the back button and bookmarks
// work properly.
export default function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
</ul>
<hr />
{/*
A <Switch> looks through all its children <Route>
elements and renders the first one whose path
matches the current URL. Use a <Switch> any time
you have multiple routes, but you want only one
of them to render at a time
*/}
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
</Switch>
</div>
</Router>
);
}
// You can think of these components as "pages"
// in your app.
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
function About() {
return (
<div>
<h2>About</h2>
</div>
);
}
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
</div>
);
}
運行出來后的頁面如下:
點擊about 跳轉(zhuǎn)到/about 頁面拷橘,如下
React Router 主要組件
React Router中的組件主要分為三類:
- 路由器局义,例如<BrowserRouter>和<HashRouter>
- 路由匹配器,例如<Route>和<Switch>
- 導(dǎo)航冗疮,例如<Link>萄唇,<NavLink>和<Redirect>
將導(dǎo)航組件視為“路線更改器”,在Web應(yīng)用程序中使用的所有組件都應(yīng)從react-router-dom導(dǎo)入术幔。
Routers
每個React Router應(yīng)用程序的核心應(yīng)該是路由器組件另萤。 對于Web項目,react-router-dom提供<BrowserRouter>和<HashRouter>路由器诅挑。 兩者之間的主要區(qū)別是它們存儲URL和與Web服務(wù)器通信的方式四敞。
- <BrowserRouter>使用常規(guī)URL路徑。 這些通常是外觀最好的URL拔妥,但是它們要求正確配置服務(wù)器忿危。 具體來說,Web服務(wù)器需要在所有由React Router客戶端管理的URL上提供相同的頁面没龙。 Create React App在開發(fā)中即開即用地支持此功能铺厨,并附帶有關(guān)如何配置生產(chǎn)服務(wù)器的說明缎玫。
- <HashRouter>將當(dāng)前位置存儲在URL的哈希部分中,因此URL看起來類似于http://example.com/#/your/page解滓。 由于哈希從不發(fā)送到服務(wù)器赃磨,因此這意味著不需要特殊的服務(wù)器配置。
要使用路由器洼裤,只需確保將其呈現(xiàn)在元素層次結(jié)構(gòu)的根目錄下即可邻辉。 通常,您會將頂級<App>元素包裝在路由器中逸邦,如下所示:
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
function App() {
return <h1>Hello React Router</h1>;
}
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
Route Matchers
有兩個router matcher: Switch
和Route
恩沛。如果使用了 <Switch>,它將搜索其子<Route>元素缕减,以查找其路徑與當(dāng)前URL匹配的元素雷客。 當(dāng)找到一個時,它將渲染該<Route>并忽略所有其他路由桥狡。 這意味著應(yīng)將有比較具體path匹配規(guī)則的<Route>放置在比較模糊匹配規(guī)則的<Route>前面搅裙。
如果沒有<Route>匹配,則<Switch>不渲染任何內(nèi)容(null)
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
function App() {
return (
<div>
<Switch>
{/* If the current URL is /about, this route is rendered
while the rest are ignored */}
<Route path="/about">
<About />
</Route>
{/* Note how these two routes are ordered. The more specific
path="/contact/:id" comes before path="/contact" so that
route will render when viewing an individual contact */}
<Route path="/contact/:id">
<Contact />
</Route>
<Route path="/contact">
<AllContacts />
</Route>
{/* If none of the previous routes render anything,
this route acts as a fallback.
Important: A route with path="/" will *always* match
the URL because all URLs begin with a /. So that's
why we put this one last of all */}
<Route path="/">
<Home />
</Route>
</Switch>
</div>
);
}
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
需要注意的是<Route path>匹配URL的開頭裹芝,而不是整個開頭部逮。 因此,<Route path =“ /”>將始終與URL匹配嫂易。 因此兄朋,我們通常將此<Route>放在<Switch>的最后。 另一種可能的解決方案是使用匹配整個URL的 <Route exact path="/">怜械。注意:盡管React Router確實支持在<Switch>之外渲染<Route>元素颅和,但從5.1版本開始,我們建議使用useRouteMatch hook代替缕允。 此外峡扩,我們不建議呈現(xiàn)不帶路徑的<Route>,而是建議使用hook來訪問所需的任何變量障本。
Navigation (or Route Changers)
React Router提供了一個<Link>組件來在應(yīng)用程序中創(chuàng)建鏈接教届。 無論在何處render<Link>,都會在HTML文檔中渲染anchor(<a>)
<NavLink>是<Link>的一種特殊類型驾霜,當(dāng)其prop與當(dāng)前位置匹配時案训,可以將其自身設(shè)置為“active”。
<Link to="/">Home</Link>
// <a href="/">Home</a>
<NavLink to="/react" activeClassName="hurray">
React
</NavLink>
// When the URL is /react, this renders:
// <a href="/react" className="hurray">React</a>
// When it's something else:
// <a href="/react">React</a>
<Redirect to="/login" />
任何時候要強制navigation粪糙,都可以使用<Redirect>萤衰。 聲依永<Redirect>時,它將使用其 to prop進行導(dǎo)航猜旬。