2020-01-03

react路由传参及其优缺点

1.params

//注意params形式都需要在路由后面加上一个动态的参数,特点是刷新地址数据依然还在,参数会在url处显示。
<Route path="/user/:name" component={User}></Route>
// 方式一:
<NavLink to="/user/alex">去user页</NavLink>
//方式二:
this.props.history.push({pathname:"/user/"+"alex"})
// 在user页获取参数的方法
this.props.match.params.name

2.search

<Route path="/follow" component={Follow}></Route>
<NavLink to="/follow?number=1212121">去follow</NavLin
//在follow获取参数的方式
this.props.location.search
    //注意得到的是带有问好的字符串(?number=1212121)一般用“query-string”插件转化为对象

3.query

//query显示不需要在路由设置里面加动态参数,特点是刷新的话数据就消失了,参数不会显示在url处
<Route path="/detail" component={Detail}></Route>
//方式一:
<NavLink to={{pathname:"/detail",query:{name:"Bob",age:18}}}>去detail</NavLink>
//方式二:
this.props.history.push({pathname:"/detail",query:{name:'小红',age:20}})
//在detail获取参数的方法
this.props.location.query.name

4.state

//state不需要在路由设置动态参数,特点是刷新数据依然保留,参数不会在url处显示
<Route path="/detail" component={Detail}></Route>
this.props.history.push({pathname:"/detail",state:{name:'小红',age:20}})
//在detail中显示数据的方法
 {this.props.location.state.name}
 {this.props.location.state.age}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容