react+react-router的搭配用起來確實爽。router4提供了很多強大的功能。這裏記錄一下通過router實現的頁面間的數據傳輸:
共有一下三種方法:
- 利用
params
傳遞
//定義路由
<Route path="/detail/:userId/:userName" component={User} />
//通過js實現頁面跳轉
this.props.history.push(`/detail/${userId}/${userName}`)
//以上是es6中模板字符串的寫法。uesrId和userName都是一個變量。渲染到頁面,瀏覽器的url可能就是 ’/detail/111/張三‘
新頁面獲取變量。假設url爲 ’/detail/111/張三‘
//router4以下的獲取方法
let {userId,userName}=this.props.params //userId="111" userName="張三"
//router4的獲取方法
let {userId,userName}=this.props.match.params //userId="111" userName="張三"
- 利用
query
傳遞
//定義路由
<Route path="/detail" component={User} />
//js頁面跳轉
this.props.history.push({
pathname:'/detail',
query:{
userId:"123",
userName:"張三"
}
})
//這種方法在頁面url中顯示爲 ’/detail‘ 不會把參數放到url中
//新頁面獲取
let {userId,userName}=this.props.location.query //userId="123" userName="張三"
- 利用
state
傳遞
//定義路由
<Route path="/detail" component={User} />
//js頁面跳轉
this.props.history.push({
pathname:'/detail',
state:{
userId:"123",
userName:"張三"
}
})
//這種方法在頁面url中顯示爲 ’/detail‘ 不會把參數放到url中
//新頁面獲取
let {userId,userName}=this.props.location.state //userId="123" userName="張三"
總結
以上三種方法都可以實現數據傳輸。但是有以下區別:
params
會把數據放到url中。而另外兩種不會。也就是說,當傳輸字段比較多的時候,第一種就有些不適用了;state
和query
看起來用法幾乎一樣。但是官方解釋說,query
會明文傳輸,state
則會加密傳輸。但是所有的數據在url中都不會出現。所以安全性不是那麼高的。query
就可以滿足了。