今天,咱們要討論的是react router中Link傳值的三種表現形式。分別爲經過通配符傳參、query傳參和state傳參。react
ps:進入正題前,先說明一下,如下的全部內容都是在react-router V4的版本下。git
Route定義方式:github
<Route path='/path/:name' component={Path}/>
Link組件:react-router
<Link to="/path/經過通配符傳參">通配符</Link>
參數獲取:this
this.props.match.params.name
注意這個match,許多博客活文章都是忽略了它,致使取不到值。這裏的this.props.match.params.name === ‘經過通配符傳參’。url
優勢:簡單快捷,而且,在刷新頁面的時候,參數不會丟失。code
缺點:只能傳字符串,而且,若是傳的值太多的話,url會變得長而醜陋。component
若是,你想傳對象的話,能夠用JSON.stringify(),想將其轉爲字符串,而後另外的頁面接收後,用JSON.parse()轉回去。這裏簡單提一下,不贅述。router
Route定義方式:對象
<Route path='/query' component={Query}/>
Link組件:
var query = { pathname: '/query', query: '我是經過query傳值 ' } <Link to={query}>query</Link>
參數獲取:
this.props.location.query
這裏的this.props.location.query === '我是經過query傳值'
優勢:優雅,可傳對象
缺點:刷新頁面,參數丟失
Route定義方式:
<Link to={state}>state</Link>
Link組件:
var state = { pathname: '/state', state: '我是經過state傳值' } <Route path='/state' component={State}/>
參數獲取:
this.props.location.state
這裏的this.props.location.state === '我是經過query傳值'
優勢:優雅,可傳對象
缺點:刷新頁面,參數丟失
如下,是我github上demo的地址,各位能夠親自嘗試一下