react router 4

React Router V4 也走了react的路,咳,一切都成組件。例如Route、Link、Switch等都是組件。
react-router和react-router-dom是react router拆分出來的,平時使用只須要引入react-router-dom,固然,若是搭配redux,你還須要使用react-router-redux。react

Router

React Router 4 中,你能夠將各類組件及標籤放進 <Router>組件中,它用來保持與 location 的同步。tips: <Router>組件下只容許存在一個子元素。能夠像如下方式使用:web

import { BrowserRouter } from 'react-router-dom'
ReactDOM.render((
  <BrowserRouter>
    <App />  //在app中進行拆分,放網站的導航連接,以及其餘的
  </BrowserRouter>
), document.getElementById('main'))
  1. <BrowserRouter>:使用 HTML5 提供的 history API(pushState,
    replaceState以及popstate事件) 來保持 UI 和 URL
    的同步,在服務區來管理動態請求時,須要使用<BrowserRouter>組件;
  2. <HashRouter>:使用 URL 的 hash (例如:window.location.hash) 來保持 UI 和 URL
    的同步,通常靜態頁面使用;
  3. <MemoryRouter>:能在內存保存你 「URL」 的歷史紀錄(並無對地址欄讀寫);
  4. <NativeRouter>:爲使用React Native提供路由支持;
  5. <StaticRouter>:從不會改變地址;

<Route>組件有以下屬性:redux

  1. path: 路由匹配路徑。(沒有path屬性的Route 老是會 匹配);
  2. exact:爲true時,則要求路徑與location.pathname必須徹底匹配,如 path='/test',你就只能匹配到'/test';
  3. strict:true的時候,有結尾斜線的路徑只能匹配有斜線的location.pathname,如path='/test/'只匹配 '/test/*';

<Route>提供了三種渲染內容的方法:react-router

  1. <Route component>:在地址匹配的時候React的組件纔會被渲染,route props也會隨着一塊兒被渲染;
  2. <Route render>:當匹配成功後調用該函數。該過程與傳入component參數相似,這種方式對於內聯渲染和包裝組件卻不引發意料以外的從新掛載特別方便;
  3. <Route children>:與render屬性的工做方式基本同樣,除了它是無論地址匹配與否都會被調用;

tips:<Route component>的優先級要比<Route render>高,一般component參數與render參數被更常常地使用。children參數偶爾會被使用,它更經常使用在path沒法匹配時呈現的'空'狀態。app

<Switch>

<Switch>會遍歷自身的子元素(即路由)並對第一個匹配當前路徑的元素進行渲染dom

import { Switch, Route } from 'react-router'

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

<Link>

當你點擊<Link>時,URL會更新,組件會被從新渲染,可是頁面不會從新加載。
Link組件屬性:ide

  1. to(string/object):要跳轉的路徑或地址;
  2. replace(bool):爲 true 時,點擊連接後將使用新地址替換掉訪問歷史記錄裏面的原地址;爲 false
    時,點擊連接後將在原有訪問歷史記錄的基礎上添加一個新的紀錄。默認爲 false;
// Link組件示例

// to爲string
<Link to="/about">關於</Link>

// to爲obj
<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>

// replace 
<Link to="/courses" replace />

React Router擁有優質的文檔,你能夠查看並從中瞭解更多的信息函數

相關文章
相關標籤/搜索