React路由實現有兩個包:javascript
1.react-router https://reacttraining.com/react-router/
css
2.react-router-dom
java
在 React 的使用中,咱們通常要引入兩個包,react
和 react-dom
,那麼 react-router
和react-router-dom
是否是兩個都要引用呢?
非也,坑就在這裏。他們兩個只要引用一個就好了,不一樣之處就是後者比前者多出了 <Link>
<BrowserRouter>
這樣的 DOM 類組件。
所以咱們只需引用 react-router-dom
這個包就好了。若是你會用到 DOM 綁定的話。react
1.項目中用到的是:算法
browserHistory和hashHistory的區別? 更改路由的方式不一樣 1.browserHistory 使用的是 HTML5 的 pushState API來修改瀏覽器的歷史記錄 2.hashHistory 是經過改變地址後面的 hash(也就是URL中#後面的值) 來改變瀏覽器的歷史記錄。 兩種方式的特色 1.History API 提供了 pushState() 和 replaceState() 方法來增長或替換歷史記錄。而 hash 沒有相應的方法,因此browserHistory有替換歷史記錄的功能,hashHistory沒有 2hashHistory實現簡單,不須要作額外的服務端改造(react browserHistory 完整部署方案:https://www.jianshu.com/p/77a5acfbc289)
跳轉到指定路徑:
<Link to="/courses" />
攜帶參數跳轉到指定路徑: <Link to={{ pathname: '/course', search: '?sort=name', state: { price: 18 } }} />
獲取路由參數:
this.props.location.state
this.props.location.search
component 只有當訪問地址和路由匹配時,一個 React component 纔會被渲染,此時此組件接受 route props (match, location, history)。 當使用 component 時,router 將使用 React.createElement 根據給定的 component 建立一個新的 React 元素。這意味着若是你使用內聯函數(inline function)傳值給 component將會產生沒必要要的重複裝載。對於內聯渲染(inline rendering), 建議使用 renderprop。 <Route path="/user/:username" component={User} /> const User = ({ match }) => { return <h1>Hello {match.params.username}!</h1> } render: func 此方法適用於內聯渲染,並且不會產生上文說的重複裝載問題。 // 內聯渲染 <Route path="/home" render={() => <h1>Home</h1} /> // 包裝 組合 const FadingRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( <FadeIn> <Component {...props} /> </FaseIn> )} /> ) <FadingRoute path="/cool" component={Something} />
children: func 有時候你可能只想知道訪問地址是否被匹配,而後改變下別的東西,而不單單是對應的頁面。 <ul> <ListItemLink to="/somewhere" /> <ListItemLink to="/somewhere-ele" /> </ul> const ListItemLink = ({ to, ...rest }) => ( <Route path={to} children={({ match }) => ( <li className={match ? 'active' : ''}> <Link to={to} {...rest} /> </li> )} )
<Route>
或 <Redirect>
。下的子節點只能是 <Route>
或 <Redirect>
元素<Redirect>
渲染時將導航到一個新地址,這個新地址覆蓋在訪問歷史信息裏面的本該訪問的那個地址。2.從Link組件和a標籤的區別提及瀏覽器
(1):對比<a>,Link組件避免了沒必要要的重渲染react-router
(2):react-router:只更新變化的部分從而減小DOM性能消耗dom
react的創新之處在於,它利用虛擬DOM的概念和diff算法實現了對頁面的"按需更新",react-router很好地繼承了這一點,譬如上圖所示,導航組件和三個Tab組件(經過...,經過...,經過...)的重渲染是咱們不但願看到的,由於不管跳轉到頁面一或是頁面二,它只須要渲染一次就夠了。<Link>組件幫助咱們實現了這個願望,反觀<a>標籤,每次跳轉都重渲染了導航組件和Tab組件試想一下,在一個浩大的項目裏,這多麼可怕!咱們的"渲染"作了許多"無用功",並且消耗了大量彌足珍貴的DOM性能!函數