react-router的理解javascript
react的一個插件庫,專門用來實現一個SPA應用(單頁Web應用(single page web application,SPA)整個應用只有一個完整的頁面,點擊頁面中的連接不會刷新頁面, 自己也不會向服務器發請求,當點擊路由連接時, 只會作頁面的局部更新)css
基於react的項目基本都會用到此庫。react-router針對不一樣的使用場景衍生了不一樣的路由包,RN項目用react-router-native,web項目用react-router-dom。而且,不須要再重複引入react-router了。html
路由的理解前端
一個路由就是一個映射關係(key:value)。key爲路由路徑, value多是function/component(某個對象的組件)java
後臺路由node
node服務器端路由, value是function, 用來處理客戶端提交的請求並返回一個響應數據react
註冊路由 router.get(path, function(req, res))。當node接收到一個請求時, 根據請求路徑找到匹配的路由, 調用路由中的函數來處理請求, 返回響應數據webpack
前臺路由git
瀏覽器端路由, value是component, 當請求的是路由path時, 瀏覽器端前沒有發送http請求, 但界面會更新顯示對應的組件github
註冊路由: <Route path="/about" component={About}>。當瀏覽器的hash變爲#about時, 當前路由組件就會變爲About組件
前端路由的實現
history庫:管理瀏覽器會話歷史(history)的工具庫。包裝的是原生BOM中window.history和window.location.hash
history API:
History.createBrowserHistory(): 獲得封裝window.history的管理對象
History.createHashHistory(): 獲得封裝window.location.hash的管理對象
history.push(): 添加一個新的歷史記錄
history.replace(): 用一個新的歷史記錄替換當前的記錄
history.goBack(): 回退到上一個歷史記錄
history.goForword(): 前進到下一個歷史記錄
history.listen(function(location){}): 監視歷史記錄的變化
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>history test</title> </head> <body> <p><input type="text"></p> <a href="/test1" onclick="return push('/test1')">test1</a><br><br> <button onClick="push('/test2')">push test2</button><br><br> <button onClick="back()">回退</button><br><br> <button onClick="forword()">前進</button><br><br> <button onClick="replace('/test3')">replace test3</button><br><br> <script type="text/javascript" src="https://cdn.bootcss.com/history/4.7.2/history.js"></script> <script type="text/javascript"> let history = History.createBrowserHistory() // 方式一 history = History.createHashHistory() // 方式二 // console.log(history) // 但願能回退使用這個方法 function push (to) { history.push(to) return false // 讓a標籤的默認行爲失效 } function back() { history.goBack() } function forword() { history.goForward() } // 但願不能夠回退使用這個方法 function replace (to) { history.replace(to) } history.listen((location) => { console.log('請求路由路徑變化了', location) }) </script> </body> </html>
react-router相關API以及基本使用
需求:實現這樣的一個簡單的路由跳轉效果
第一步:搭建一個應用,目錄結構何文件以下
第二步:項目中下載react-router
對於web應用,咱們只須要安裝react-router-dom,不過在
node_modules
下你依然會看到react-router
的身影,這是react-router-dom
依賴的包,另外還有一個history
包
npm install --save react-router-dom
第三步:index.js項目入口文件中使用路由管理整個應用
<Router>是實現路由最外層的容器,通常狀況下咱們再也不須要直接使用它,而是使用在它基礎之上封裝的幾個適用於不一樣環境的組件,react-router-dom的Router有四種:
通常咱們不多會用到<MemoryRouter>和<StaticRouter>,在web應用中更多的是用react-router-dom
擴展出來的<BrowserRouter>和<HashRouter>
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter, HashRouter} from 'react-router-dom' import './index.css'; import App from './App'; ReactDOM.render(( <BrowserRouter> <App /> </BrowserRouter> ), document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA
或者可使用HashRouter模式
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter, HashRouter} from 'react-router-dom' import './index.css'; import App from './App'; ReactDOM.render(( <HashRouter> <App /> </HashRouter> ), document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA
<BrowserRouter>和<HashRouter>使用注意點,<HashRouter>生成的url路徑看起來是這樣的:
http://localhost:8080/#/user
咱們知道hash值是不會傳到服務器端的,因此使用hash記錄狀態不須要服務器端配合,可是<BrowserRouter>生成的路徑是這樣的:
http://localhost:8080/user
這時候在此目錄下刷新瀏覽器會從新向服務器發起請求,服務器端沒有配置這個路徑,因此會出現can't GET /user
這種錯誤,而解決方法就是,修改devServer的配置,webpack.config.js
devServer: { publicPath: publicPath, contentBase: path.resolve(__dirname, 'build'), inline: true, hot: true, historyApiFallback: true, //增長 },
第四步:建立測試路由的模塊頁面,而且在App.js中引入
import React, { Component } from 'react'; import './App.css'; import RouterTest from './views/router-test/router-test' class App extends Component { render() { return ( <div className="App"> <RouterTest/> </div> ); } } export default App;
第五步:路由測試模塊router-test.js中使用<NavLink/>來包裹路由鏈接,而且使用<Switch>來匹配路由組件(若是隻有一個路由組件,就不用這個標籤了),<Redirect/>設置一打開就定向到某個路由
import React, { Component } from 'react'; import {NavLink, Switch, Route, Redirect} from 'react-router-dom' import './router-test.css'; import About from '../about/about' import Home from '../home/home' class RouterTest extends Component { render() { return ( <div className="router-test"> <div className='router-list'> <NavLink className='router-list-group' to='/home'>HOME</NavLink> <NavLink className='router-list-group' to='/about'>ABOUT</NavLink> </div> <div className='router-content'> <Switch> <Route path='/about' component={About} /> <Route path='/home' component={Home} /> <Redirect to='/home'/> </Switch> </div> </div> ); } } export default RouterTest;
<Route>說明:path,exact,strict:path
是用於指定路徑名的,exact
和strict
是匹配路徑名時指定更爲嚴格的匹配規則,其匹配原則用的是path-to-regexp。,若是<Route>不寫path則老是能被匹配
<NavLink>和<Link>說明:前面的<Route>
提供了路由配置,<NavLink>
和<Link>
就是能夠訪問這些路由的組件,也就是:
<NavLink>和 <Link>的區別:它倆都是react-router-dom
提供的組件,<NavLink>
是在<Link>
上面擴展了當路由匹配時添加樣式屬性,而這更經常使用,因此建議直接使用<NavLink>
.
Route path => path //to能夠是對象也能夠是字符串 NavLink(Link) to => location or location.pathname
總結:整個路由棧匹配就是在圍繞path
和location.pathname
這兩個東西,其中,<Route>
組件負責path
, <NavLink>
(<Link>
)組件負責location.pathname
about.js組件
import React, { Component } from 'react'; import './about.css'; class About extends Component { render() { return ( <div className="about"> about </div> ); } } export default About;
home.js組件
import React, { Component } from 'react'; import './home.css'; class Home extends Component { render() { return ( <div className="home"> home </div> ); } } export default Home;
第六步:運行後,<NavLink/>標籤會解析成a標籤,當前激活的那個路由,會有一個class類:active
第七步(擴展):這個類能夠自定義,而後能夠在activeClass類中編寫樣式
<NavLink className='router-list-group' activeClassName='activeClass' to='/home'>HOME</NavLink> <NavLink className='router-list-group' activeClassName='activeClass' to='/about'>ABOUT</NavLink>
第八步(優化擴展):可是這樣每一個路由連接都要這樣寫一個自定義類很麻煩,這時候咱們能夠將NavLink組件包裝一下,定義一個公共組件
編寫my-nav-link.js組件
import React from 'react' import {NavLink} from 'react-router-dom' export default function MyNavLink(props) { /*包裝一個現有的組件,{...props}表示接收任何屬性*/ return <NavLink {...props} activeClassName='activeClass'/> }
而後應用這個公共的組件
import React, { Component } from 'react'; import {Switch, Route, Redirect} from 'react-router-dom' import MyNavLink from '../../components/my-nav-link/my-nav-link' import './router-test.css'; import About from '../about/about' import Home from '../home/home' class RouterTest extends Component { render() { return ( <div className="router-test"> <div className='router-list'> <MyNavLink className='router-list-group' to='/home'>HOME</MyNavLink> <MyNavLink className='router-list-group' to='/about'>ABOUT</MyNavLink> </div> <div className='router-content'> <Switch> <Route path='/about' component={About} /> <Route path='/home' component={Home} /> <Redirect to='/home'/> </Switch> </div> </div> ); } } export default RouterTest;
運行結果顯示,當前激活的路由就會帶上activeClass這個類
路由的嵌套
其實跟上面基本上是同樣的
import React, { Component } from 'react'; import './home.css'; import {Switch, Route, Redirect} from 'react-router-dom' import MyNavLink from '../../components/my-nav-link/my-nav-link' import News from './news/news' import Message from './messages/messages' class Home extends Component { render() { return ( <div className="home"> <ul className="nav nav-tabs"> <li> <MyNavLink to='/home/news'>News</MyNavLink> </li> <li> <MyNavLink to="/home/message">Message</MyNavLink> </li> </ul> <Switch> <Route path='/home/news' component={News} /> <Route path='/home/message' component={Message} /> <Redirect to='/home/news'/> </Switch> </div> ); } } export default Home;
下面是兩個路由組件
import React, { Component } from 'react'; import './news.css'; class News extends Component { render() { return ( <div className="news"> news </div> ); } } export default News;
import React, { Component } from 'react'; import './messages.css'; class Messages extends Component { render() { return ( <div className="messages"> messages </div> ); } } export default Messages;
向路由組件傳遞數據
在路由組件home.js組件中再建兩個子路由組件,而且引入,使用導航路由去連接,而且傳入參數
import React, { Component } from 'react'; import './home.css'; import {Switch, Route, Redirect} from 'react-router-dom' import MyNavLink from '../../components/my-nav-link/my-nav-link' import News from './news/news' import Message from './messages/messages' class Home extends Component { state = { id: 2, title: 'messagesssss' } render() { // const path = this.props.match.path // 獲取當前組件的路由地址 // console.log(path) // /home return ( <div className="home"> <ul className="nav nav-tabs"> <li> {/*路由連接*/} <MyNavLink to={`/home/news/${this.state.id}`}>News</MyNavLink> </li> <li> {/*非路由連接,點擊的時候會發起請求*/} <a href={`/home/message/${this.state.title}`}>Message</a> </li> </ul> <Switch> {/*id表示下級的路由組件裏用來接收參數的名字*/} <Route path={`/home/news/:id`} component={News} /> <Route path={`/home/message/:title`} component={Message} /> {/*一樣在這個重定向裏也要帶上參數*/} <Redirect to={`/home/news/${this.state.id}`} /> </Switch> </div> ); } } export default Home;
import React, { Component } from 'react'; import './news.css'; class News extends Component { componentDidMount (){ const idStr = this.props.match.params.id console.log(idStr) const path = this.props.match.path console.log(path) } render() { return ( <div className="news"> news </div> ); } } export default News;
運行結果顯示拿到了傳過來的id
多種路由跳轉方式
replace方式,push方式(默認方式),<Link>和<NavLink>
import React, { Component } from 'react'; import './home.css'; import {Switch, Route, Link, Redirect} from 'react-router-dom' import MyNavLink from '../../components/my-nav-link/my-nav-link' import News from './news/news' import Message from './messages/messages' class Home extends Component { state = { id: 2, title: 'messagesssss' } showNews (id) { this.props.history.push(`/home/news/${id}`) } showMessage (title) { this.props.history.replace(`/home/message/${title}`) } back = () => { this.props.history.goBack() } forward = () => { this.props.history.goForward() } reqPage = () => { window.location = 'http://www.baidu.com' } render() { return ( <div className="home"> <Link to={`/home/news/${this.state.id}`}>News</Link> <button onClick={() => {this.showNews(this.state.id)}}>NEWS push方式</button> <button onClick={() => {this.showMessage(this.state.title)}}>MESSAGE replace方式</button> <Switch> {/*id表示下級的路由組件裏用來接收參數的名字*/} <Route path={`/home/news/:id`} component={News} /> <Route path={`/home/message/:title`} component={Message} /> {/*一樣在這個重定向裏也要帶上參數*/} <Redirect to={`/home/news/${this.state.id}`} /> </Switch> <p> <button onClick={this.back}>返回</button> <button onClick={this.forward}>前進</button> </p> <p> <button onClick={this.reqPage}>整個頁面的跳轉</button> </p> </div> ); } } export default Home;
<Router>的實現源碼分析
<Router>的實現源碼來看看路由到底傳了些什麼東西。
class Router extends React.Component { //檢測接收的參數 static propTypes = { history: PropTypes.object.isRequired, //必須傳入 children: PropTypes.node } //設置傳遞給子組件的屬性 getChildContext() { return { router: { ...this.context.router, history: this.props.history, //核心對象 route: { location: this.props.history.location, //history裏的location對象 match: this.state.match //當路由路徑和當前路徑成功匹配,一些有關的路徑信息會存放在這裏,嵌套路由會用到它。 } } } } state = { match: this.computeMatch(this.props.history.location.pathname) } computeMatch(pathname) { return { path: '/', url: '/', params: {}, //頁面間傳遞參數 isExact: pathname === '/' } } }
這裏面最重要的就是須要咱們傳入的history對象,我前面提到過咱們通常不會直接使用<Router>
組件,由於這個組件要求咱們手動傳入history
對象,但這個對象又很是重要,並且不一樣的開發環境須要不一樣的history
,因此針對這種狀況react-router
才衍生了兩個插件react-router-dom
和react-router-native
(我認爲這是比較重要的緣由,瀏覽器有一個history對象,因此web應用的路由都是在此對象基礎上擴展的)。
接着讓咱們來看一下react-router-dom
用到的來自history的兩個方法:
createBrowserHistory 適用於現代瀏覽器(支持h5 history API)
createHashHistory 適用於須要兼容老版本瀏覽器的狀況
這兩個方法就分別對應了兩個組件:<BrowserRouter>
和<HashRouter>
,它倆返回的history
對象擁有的屬性是同樣的,可是各自的實現不一樣。
//createHashHistory.js var HashChangeEvent = 'hashchange'; //hash值改變時會觸發該事件 var createHashHistory = function createHashHistory() { var globalHistory = window.history; //全局的history對象 var handleHashChange = function handleHashChange() {} //hash值變化時操做的方法 } //createBrowserHistory.js var PopStateEvent = 'popstate'; //監聽url的變化事件 var HashChangeEvent = 'hashchange'; //依然監聽了hash改變的事件,可是多加了一個判斷是是否須要監聽hash改變,若是不須要就不綁定該事件。 var createBrowserHistory = function createBrowserHistory() { var globalHistory = window.history; //全局的history對象 var handlePop = function handlePop(location) {} //出棧操做 } //createHashHistory.js,createBrowserHistory.js導出的history對象 const history = { length: globalHistory.length, //globalHistory就是window.history action: "POP", //操做歷史狀態都屬於出棧操做 location: initialLocation, //最重要的!!前面的Router.js源碼向子組件單獨傳遞了這個對象,由於路由匹配會用到它。 createHref, //生成的url地址樣式,若是是hash則加一個'#' push, //擴展history.pushState()方法 replace, //擴展history.replaceState()方法 go, //history.go()方法 goBack, //history.back()方法 goForward, //history.forward()方法 block, listen }
咱們從控制檯打印一下看看這個history
:
因此,咱們直接用<BrowserRouter>
與使用<Router>
搭配createBrowserHistory()
方法是同樣的效果。
import { Router, } from 'react-router-dom' import createBrowserHistory from 'history/createBrowserHistory'; const history = createBrowserHistory(); const App = () => ( <Router history={history}> <div>{/*其它*/}</div> </Router> )
import { BrowserRouter, } from 'react-router-dom' const App = () => ( <BrowserRouter> <div>{/*其它*/}</div> </BrowserRouter> )