react router v4 簡介

最近使用react router 遇到一個問題:當對某個路由添加參數的時候/list/:app 這列路由,點擊這個路由之後再點擊其餘路由,location地址就追加到後面,問不是replace.react

/list/:app => /list/appName

切換到/info 就變成了/list/appName/info

最後經過定位,發覺是在Link的時候對Link的to沒有添加絕對地址的緣由。app

<Link to="list/appName" /> 要修改成<Link to="/list/appName" />

在定位這個問題的時候,看了一下各個部分的源代碼,下面對react router v4作一個簡單的介紹。ide

分別從route, history, location, match 作介紹。函數

route

一、route 三種render方式:component, render, function
二、route的props: match, location, history
三、router的path當不指定path的時候就會一直匹配ui

route path 匹配寫法:this

<Route path='tasks_list/:app/:jobId' component={component} />

若是params 是可選的寫法:url

<Route path='tasks_list/:app/:jobId?' component={component} />

history

history 是一個路由中最重要的部分,通常來講用戶只有兩種方式會更新當前 URL。一種是用戶點擊了某個錨標籤或者直接操做 history 對象的 replace/push 方法;另外一種是用戶點擊前進/後退按鈕。不管哪種方式都要求咱們的路由系統可以實時監聽 URL 的變化,而且在 URL 發生變化時及時地作出響應,渲染出正確的頁面。咱們首先來考慮下如何處理用戶點擊前進/後退按鈕。React Router 使用 History 的 .listen 方法來監聽當前 URL 的變化,其本質上仍是直接監聽 HTML5 的 popstate 事件。
當監聽到 popstate 事件被觸發時,咱們會調用 forceUpdate 函數來強制進行重渲染。總結而言,不管咱們在系統中設置了多少的路由組件,它們都會獨立地監聽 popstate 事件而且相應地執行重渲染操做。接下來咱們繼續討論 matchPath 這個 Route 組件中相當重要的函數,它負責決定當前路由組件的 path 參數是否與當前 URL 相一致。code

react router 的history 是調用了ReactTraining的history
react router 的history有如下屬性與方法:component

  1. length - (number) The number of entries in the history stack
  2. action - (string) The current action (PUSH, REPLACE, or POP)
  3. location - (object) The current location. May have the following properties:

1) pathname - (string) The path of the URL
2)search - (string) The URL query string
3)hash - (string) The URL hash fragment
4)state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.router

1)push(path, [state]) - (function) Pushes a new entry onto the history stack
2)replace(path, [state]) - (function) Replaces the current entry on the history stack    
3)go(n) - (function) Moves the pointer in the history stack by n entries
4)goBack() - (function) Equivalent to go(-1)    
5)goForward() - (function) Equivalent to go(1)
6)block(prompt) - (function) Prevents navigation (see the history docs)

location

location指定當前的app在哪兒
Route component as this.props.location
Route render as ({ location }) => ()
Route children as ({ location }) => ()
withRouter as this.props.location
好比上面遇到的問題,就是location的問題,最後定位到是createLocation的方法出的問題。

match

有了location, 而後有了route, match包含的信息就是 <Route path>如何匹配當前的location

  1. params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
  2. isExact - (boolean) true if the entire URL was matched (no trailing characters)
  3. path - (string) The path pattern used to match. Useful for building nested <Route>s
  4. url - (string) The matched portion of the URL. Useful for building nested <Link>

Redirect

這個組件並無真實地進行界面渲染,而是僅僅進行了簡單的跳轉操做

相關文章
相關標籤/搜索