React路由传参

您好,如果你看到这篇文章,不知可否留下您宝贵的意见!!!

当我们要进行跳转的时候,通常会把一些参数传到另一个组件上去,以便跳转到的组件可以轻而易举的拿到参数。通常通过params、query、state以及search这四种方法进行传参,接下来让我给你们演示一下:

1.Params

<Route path='/path/:id' component={Path}/> //path指路径;component指所跳转的组件
<link to="/path/otherRouter">你好!我是跳转到的路由</Link>
this.props.history.push({pathname:"/path/" + id});
读取参数用:this.props.match.params.id

优势:当刷新地址栏的时候,参数依旧存在。
缺点:只能传字符串,当传的值过多的话,会显得url变得长并且丑陋。

query

<Route path='/query' component={Query}/>
<Link to={{ path : ' /query' , query : { age: 11 }}}> //pash是路径,query是参数
this.props.history.push({pathname:"/query",query: { age: 11 }});
读取参数用: this.props.location.query.age

优点:可以传对象并且变得更优雅。
缺点:不能刷新地址栏,不然参数会丢失。

state

<Route path='/sort ' component={Sort}/>
<Link to={{ path : ' /sort ' , state : { age: 11 }}}> 
this.props.history.push({pathname:"/sort ",state : { age: 11 }});
读取参数用: this.props.location.query.state 

优缺点和query相同

search

<Route path='/router/searchRouter' component={SearchRouter}/>
<link to="/router/searchRouter?id=12138">xxx</Link>
this.props.history.push({pathname:"/router/searchRouter?id" + id});
读取参数用: this.props.location.search

优缺点和params相同

中国加油!武汉加油!

千峰逆战

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值