背景,找到一篇博文写的关于路由传参,但是该片博文中有一些错误的信息,所以在下重新整理了一下内容
这是参考的博文地址https://www.jianshu.com/p/ad8cc02b9e6c
1.params
<Route path='/path/:name' component={Path}/>
<link to="/path/2">xxx</Link>
this.props.history.push({pathname:"/path/" + name});
读取参数用:this.props.match.params.name
优势 : 刷新地址栏,参数依然存在
缺点:只能传字符串,并且,如果传的值太多的话,url会变得长而丑陋。
2.query
<Route path='/query' component={Query}/>
<Link to={{ pathname: ' /query' , query : { name : 'sunny' }}}>
this.props.history.push({pathname:"/query",query: { name : 'sunny' }});
读取参数用: this.props.location.query.name
优势:传参优雅,传递参数可传对象;
缺点:刷新地址栏,参数丢失
3.state
<Route path='/sort ' component={Sort}/>
<Link to={{ pathname: ' /sort ' , state : { name : 'sunny' }}}>
this.props.history.push({pathname:"/sort ",state : { name : 'sunny' }});
读取参数用: this.props.location.state.name
优缺点同query
4.search
<Route path='/web/departManange ' component={DepartManange}/>
<link to="web/departManange?name=小伙">xxx</Link>
this.props.history.push({pathname:"/web/departManange?name=小伙"});
读取参数用: this.props.location.search //结果:?name=小伙
let url=this.props.location.search
let sx=url.slice(1)
let sub=sx.split('&')
let obj={}
sub.forEach(item=>{
let ius=item.split('=')
obj[ius[0]]=ius[1]
})
console.log(obj) //结果: {name: "小伙"}
优缺点同params