react路由传参(3种⽅式)1、params传参(刷新页⾯后参数不消失,参数会在地址栏显⽰)
路由页⾯:<Route path='/demo/:id' component={Demo}></Route> //注意要配置 /:id
路由跳转并传递参数:
链接⽅式:<Link to={'/demo/'+'6'}>XX</Link>
react router6或:<Link to={{pathname:'/demo/'+'6'}}>XX</Link>
js⽅式:this.props.history.push('/demo/'+'6')
或:this.props.history.push({pathname:'/demo/'+'6'})
获取参数:this.props.match.params.id //注意这⾥是match⽽⾮history
1、params传参(多个动态参数)
state={
id:88,
name:'Jack',
}
路由页⾯:<Route path='/demo/:id/:name' component={Demo}></Route>
路由跳转并传递参数:
链接⽅式:<Link to={{pathname:`/demo/${this.state.id}/${this.state.name}`}}>XX</Link>
js⽅式:this.props.history.push({pathname:`/demo/${this.state.id}/${this.state.name}`})
获取参数:this.props.match.params //结果 {id: "88", name: "Jack"}
2、query传参(刷新页⾯后参数消失)
路由页⾯:<Route path='/demo' component={Demo}></Route> //⽆需配置
路由跳转并传递参数:
链接⽅式:<Link to={{pathname:'/demo',query:{id:22,name:'dahuang'}}}>XX</Link>
js⽅式:this.props.history.push({pathname:'/demo',query:{id:22,name:'dahuang'}})
获取参数: this.props.location.query.name
3、state传参( 刷新页⾯后参数不消失,state传的参数是加密的,⽐query传参好⽤)
注:state 传参的⽅式只⽀持Browserrouter路由,不⽀持hashrouter
路由页⾯:<Route path='/demo' component={Demo}></Route> //⽆需配置
路由跳转并传递参数:
链接⽅式: <Link to={{pathname:'/demo',state:{id:12,name:'dahuang'}}}>XX</Link>
js⽅式:this.props.history.push({pathname:'/demo',state:{id:12,name:'dahuang'}})
获取参数: this.props.location.state.name
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论