React 路由传参的三种方式

一、params传参

  • 刷新页面后参数不消失
  • 参数会在地址栏显示
  • 需要在Route中配置参数名称

1、params传递单个参数

路由页面

<Route path="/production/:productionId" component={production} />
  • 使用Link传参
<Link to={‘/production/’ + '105'}>跳转</Link>

或者

<Link to={{pathname: '/production/' + '105'}}>跳转</Link>
  • 使用js传参
this.props.history.push('/production/'+'105');

或者

this.props.history.push({pathname:'/production/'+'6'});

获取参数

this.props.match.params.productionId

2、params传递多个参数

路由页面

<Route path='/production/:productionId/:productionType' component={production}></Route>
state = {
     productionId: 120,
     productionType: 'fruits'
 }
  • 使用Link传参
<Link to={{pathname:`/production/${this.state.productionId}/${this.state.productionType}`}}>跳转</Link>
  • 使用js传参
this.props.history.push({pathname:`/demo/${this.state.productionId}/${this.state.productionType}`});

获取参数

this.props.match.params

二、query传参

  • 刷新页面后参数消失
  • 参数不会在地址栏显示

路由页面(无需配置)

<Route path='/production' component={production}></Route>
  • 使用Link传参
<Link to={{pathname:'/production',query:{productionId:120,productionType:'fruits'}}}>跳转</Link>
  • 使用js传参
this.props.history.push({pathname:'/production',query:{productionId:120,productionType:'fruits'}});

获取参数

this.props.location.query

三、state传参

  • 刷新页面后参数不消失
  • 参数不会在地址栏显示

路由页面(无需配置)

<Route path='/production' component={production}></Route>
  • 使用Link传参
<Link to={{pathname:'/production',state:{productionId:12,productionType:'fruits'}}}>跳转</Link>
  • 使用js传参
this.props.history.push({pathname:'/production',state:{productionId:12,productionType:'fruits'}});

获取参数

this.props.location.state

如果觉得本文对您有帮助的小伙伴可以积极留言或者点赞!🍉🍉🍉

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容