React成长路之踩坑路:react-router4路由传参(@react-router4.3.1)

在react-router@4中传参有三种方式

一、通过params传参:

  1、在路由表中:

<Route path="/search/:type/:keyword?" component={Search} />

  2、Link处使用:

<Link to={'/detail/' + data.id}>

  3、js处使用

this.props.history.push('/detail/' + id)    //页面跳转
this.props.history.replace('/detail/' + id)   //参数改变重新当前页面渲染

  4、参数获取

console.log(this.props.match.params)

这种方法有两个注意点,与2、3区别:

  11、<Route path="/search/:type(/:keyword)" component={Search} />   //2\3路由的可选参数keyword

    <Route path="/search/:type/:keyword?" component={Search} />   // 4路由可选参数是这样的

  12、this.props.history.push('/detail/' + id)    //2/3中可实现页面的反复渲染,在4中就会报错,用该用replace代替

  13、this.props.params    //在2/3可获取到传递过来的参数,而在4中会抱undefined的错会,改用this.props.match.params即可

二、通过query传参

  1、Link处使用:

<Link to={{pathname:'/detail/',query:{'id': data.id} }}>

  2、js处引用:

this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

  3、参数获取:

console.log(this.props.location.query) //获取到传递过来的query对象

三、通过state传参

  1、Link处使用

<Link to={{pathname:'/detail/',query:{'id': data.id} }}>

  2、js处引用

this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

  3、参数获取

console.log(this.props.location.state) //获取到传递过来的query对象

注:query与state传参异同点

  同:

  1、不需要配置路由表

  2、必须有其它页面跳转过来才能获取参数,当前页面刷新,参数清空

  异:

  1、state传参是加密的,query是公开的,显示在地址栏

 

  

  

转载于:https://www.cnblogs.com/bella-lin/p/10026067.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值