react路由传参,以及优缺点 带例子

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={{ path : ' /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={{ path : ' /sort ' , state : { name : 'sunny' }}}/>
this.props.history.push({pathname:"/sort ",state : { name : 'sunny' }});

读取参数用: this.props.location.query.state

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

4.search

<Route path='/web/departManange ' component={DepartManange}/>
<link to="web/departManange?tenantId=12121212">xxx</Link>

this.props.history.push({pathname:"/web/departManange?tenantId" + row.tenantId});

读取参数用: this.props.location.search

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

下面是一个路由跳转的例子

传参页面

export default class Login extends Component {
 在这个点击的事件里去路由跳转,另一个页面去接收
  dj(id) {
    console.log(id)
    this.props.history.push({
      pathname: '/detail',
      state: id
    })
  }
  render() {
    return (
      <div>
        <h2>Login 登录页</h2>
        {
          this.state.list.map((mv) => (
          //在这个写点击事件
            <div key={mv.id} onClick={() => this.dj(mv.id)}>
              <img src={mv.img} style={{ width: '100px', height: '159px' }} className="img-responsive" alt="" />
              <p >{mv.tCn}</p>
            </div>
          ))
        }
      </div>
    )
  };
}

接收页面 this.props.location.state

componentDidMount() {
    fetch('https://url.api?locationId=290&movieId=' + this.props.location.state)
      .then(res => res.json())
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值