1.params传参(刷新页面后参数不消失,参数会在地址栏显示)
代码展示:
/* 向路由组件传递params参数 */
//声明式路由跳转:
<Link to={`/home/message/detail/${id}/${title}`}>{title}</Link>
//或
<Link to={{pathname:`/home/message/detail/${id}/${title}`}}>{title}</Link>
//编程式路由跳转:
this.props.history.push(`/home/message/detail/${id}/${title}`)
//或
this.props.history.push({pathname:`/home/message/detail/${id}/${title}`})
/* 声明接收params参数 */
<Route path="/home/message/detail/:id/:title" component={Detail}/>
// 接收params参数
const {id,title} = this.props.match.params
2.search传参(刷新页面后参数不消失,参数会在地址栏显示)
代码展示:
/* 向路由组件传递search参数 */
//声明式路由跳转
<Link to={`/home/message/detail/?id=${id}&title=${title}`}>{title}</Link>
//或
<Link to={{pathname:`/home/message/detail/?id=${id}&title=${title}`}}>{title}</Link>
//编程式路由跳转:
this.props.history.push(`/home/message/detail?id=${id}&title=${title}`)
//或
this.props.history.push({pathname:`/home/message/detail?id=${id}&title=${title}`})
/* search参数无需声明接收,正常注册路由即可 */
<Route path="/home/message/detail" component={Detail}/>
// 接收search参数
import qs from 'querystring'
const {search} = this.props.location
const {id,title} = qs.parse(search.slice(1))
备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
项目安装 querystring插件
npm i -save-dev querystring
在需要接收参数的页面引入
import qs from 'querystring'
使用qs解析编码
const {search} = this.props.location
const {id,title} = qs.parse(search.slice(1))
3.query传参(刷新页面后参数消失,参数不会在地址栏显示)
代码展示:
/* 向路由组件传递query参数 */
//声明式路由跳转
<Link to={{pathname:'/home/message/detail',query:{id,title}}}>{title}</Link>
//编程式路由跳转
this.props.history.push({pathname:`/home/message/detail`,query:{id,title}})
/* query参数无需声明接收,正常注册路由即可 */
<Route path="/home/message/detail" component={Detail}/>
//接收query参数
const {id,title} = this.props.location.query
4.state传参(刷新页面后参数不会消失,参数也不会在地址栏显示)
代码展示:
/* 向路由组件传递state参数 */
//声明式路由跳转
<Link to={{pathname:'/home/message/detail',state:{id,title}}}>{title}</Link>
//编程式路由跳转
this.props.history.push(`/home/message/detail`,{id,title})
//或
this.props.history.push({pathname:`/home/message/detail`,state:{id,title}})
/* query参数无需声明接收,正常注册路由即可 */
<Route path="/home/message/detail" component={Detail}/>
//接收query参数
const {id,title} = this.props.location.state