react-router V4中的url參數

概述

以前寫過react在router中傳遞數據的2種方法,可是有些細節沒有理清楚,如今補上,記錄下來,供之後開發時參考,相信對其餘人也有用。html

參考資料:stackoverflow react router redux urlreact

match

若是使用下面這種方式切換路由,那麼參數能夠經過props.match.params.filter拿到。redux

<Route path='/:filter' component={App} />

<Link to='active'> Active </Link>

不過要注意2點:react-router

  1. filter能夠變成其它參數,這個時候props.match.params.filter裏面的filter也要變成相應的參數。
  2. 只能在component={App}裏面的App組件中經過props拿到filter這個參數,在其它組件中拿不到。(即不是組件自身渲染時經過解析url拿到參數的,而是經過props傳遞過來的。)

location

若是使用下面這種方式切換路由,那麼參數data能夠經過props.location.data.name拿到。url

const linkActive = {
    pathname: 'active',
    data: {name: 'haha'}
}

<Route path='/:filter' component={App} />

<Link to={ linkActive }> Active </Link>

注意:spa

  1. 若是要拿filter仍是經過props.match.params.filter拿到。
  2. 只能在component={App}裏面的App組件中經過這種方式拿參數。

其它

那麼咱們怎麼在App以外的組件中得到這個參數呢?.net

  1. 一個辦法是讓App組件經過傳遞props給這個組件。
  2. 另外一個辦法是讓App組件把這個參數存入redux裏面。
  3. 還有一個辦法是在這個組件前面加一個路由。(猜測的,沒試過)好比這麼使用:
<Route path='/:filter' component={List} />
<List />
相關文章
相關標籤/搜索