React 獲取 url 參數 —— this.props.match

在 react 組件的  componentDidMount 方法中打印一下 this.props,在瀏覽器控制檯中查看輸出以下:react

 

其中頁面的 url 信息全都包含在 match 字段中,以地址瀏覽器

localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7

爲例,其中各個參數定義對應以下:session

localhost:3000/app/knowledgeManagement/modify/:studyNo/:stepId/:randomNum/:isDefault/?s=&f=

首先打印 this.props.match :react-router

能夠看到 this.props.match 中包含的 url 信息仍是很是豐富的,其中app

  • history:包含了組件能夠使用的各類路由系統的方法,經常使用的有 push 和 replace,二者都是跳轉頁面,可是 replace 不會引發頁面的刷新,僅僅是改變 url。
  • location:至關於URL 的對象形式表示,經過 search 字段能夠獲取到 url 中的 query 信息。(這裏 state 的含義與 HTML5 history.pushState API 中的 state 對象同樣。每一個 URL 都會對應一個 state 對象,你能夠在對象裏存儲數據,但這個數據卻不會出如今 URL 中。實際上,數據被存在了 sessionStorage 中)(參考: 深刻理解 react-router 路由系統
  • match:包含了具體的 url 信息,在 params 字段中能夠獲取到各個路由參數的值。

經過以上分析,獲取 url 中的指定參數就十分簡單了,下面是幾個例子:dom

// localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7
// localhost:3000/app/knowledgeManagement/modify/:studyNo/:stepId/:randomNum/:isDefault/?s=1&f=7

// 獲取 studyNo
this.props.match.match.params.studyNo // STY20171011124209535

// 獲取 stepId
this.props.match.match.params.stepId // 3

// 獲取 success
const query = this.props.match.location.search // '?s=1&f=7'
const arr = query.split('&') // ['?s=', 'f=7']
const successCount = arr[0].substr(3) // '1'
const failedCount = arr[1].substr(2) // '7'
相關文章
相關標籤/搜索