react 路由传参及获取参数

1.params
优势 : 刷新地址栏,参数依然存在
缺点:只能传字符串,并且,如果传的值太多的话,url会变得长而丑陋。

传参

import { Link, Route, Switch } from 'react-router-dom'
   <Link key={listObj.id}
              to={`/home/home_news/detail/${listObj.id}/${listObj.content}/${listObj.age}`}
              >{listObj.content}</Link>

声明接收params参数

<Route path='/home/home_news/detail/:name/:count/:age' component={home_content}/>

读取参数

let { age, name, count } = this.props.match.params

2.query

优势:传参优雅,传递参数可传对象;
缺点:刷新地址栏,参数丢失

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


4.search
优缺点同params

  <Link key={listObj.id}
              to={`/home/home_news/detail/?id=${listObj.id}&title=${listObj.content}`}
              >{listObj.content}</Link>
`
search接收
``
<Route path='/home/home_news/detail' component={home_content}/>

读取参数
   import qs from 'querystring'
    let { search } = this.props.location
    let result = qs.parse(search.slice(1))
    let { id, title } = result
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值