使用方法
- 在入口文件(這里是
index.js
)中加入如下代碼
import { HashRouter, Route, Switch }from 'react-router-dom';
- 在原來的基礎(chǔ)上加入路由配置
<HashRouter>...<HashRouter/>
<div className="App">
<Header />
// start
<HashRouter>
<Switch>
<Route exact path="/" component={Index} />
<Route exact path="/suc" component={Suc} />
</Switch>
</HashRouter>
// end
</div>
相關(guān)知識(shí)
-
react-router
和react-router-dom
異同
-
react-router
: 實(shí)現(xiàn)了路由的核心功能;
-
react-router-dom
: 基于react-router
,加入了在瀏覽器運(yùn)行環(huán)境下的一些功能,例如:Link
組件,會(huì)渲染一個(gè)a
標(biāo)簽,Link組件源碼a
標(biāo)簽行; BrowserRouter
和HashRouter
組件,前者使用pushState
和popState
事件構(gòu)建路由,后者使用window.location.hash
和hashchange
事件構(gòu)建路由;
-
react-router-dom
依賴react-router
;
-
<HashRouter>
使用 URL 的 hash (例如:window.location.hash) 來保持 UI 和 URL 的同步;
-
<BrowserRouter>
使用 HTML5 提供的 history API 來保持 UI 和 URL 的同步;
-
<Switch>
用于渲染與路徑匹配的第一個(gè)子 <Route>
或 <Redirect>
。它的獨(dú)特之處是獨(dú)它僅僅渲染一個(gè)路由。相反地,每一個(gè)包含匹配地址(location)的<Route>
都會(huì)被渲染。
<Switch>
尋找到匹配的<Route>
之后將停止尋找匹配并渲染該<Route>
。
-
exact
精準(zhǔn)匹配。如果為 true,則只有在位置完全匹配時(shí)才應(yīng)用激活類/樣式。
例如在開始到例子中,只有/suc
才會(huì)匹配成功,/suc/test
則不會(huì)。
TIPS
-
<...Router>
組件下只能有一個(gè)根目錄