react-router 传参

本文介绍了 react-router 传参的方法,适用于 4.0 以上和以下版本。详细阐述了通过 params、query、state 三种方式传参的路由配置、使用方法及取值方式,还指出了 query 和 state 传参在页面刷新时的缺点,最后介绍了 react-router 2.0 和 4.0 中可选参数的写法。

前提:

react-router或react-router-dom4.0以上版本使用方法:

this.context.router.history.push('/users');

react-router或react-router-dom4.0以下版本使用方法:

this.context.router.push('/users');

传参:

(以下都是采用4.0以上版本写法)

1.通过params传参:

在路由中配置:

 <Route path=' /editUser/:id '   component={EditUser}></Route>

使用时在link处配置:

 <Link to={ `/editUser/admin`} >编辑用户</Link>          

或者使用时在js处调用:

this.context.router.history.push(`/system/editUser/admin`);

取值方式:

在页面中,通过

const {id} = this.props.match.params;

或者

const id = this.props.match.params.id;

取值。

2.通过query传参:

在路由中配置:

 <Route path=' /editUser '   component={EditUser}></Route>

使用时在link处配置:

 <Link to={{ path : ' /editUser' , query : { id: 'admin' }}}>编辑用户</Link>          

或者使用时在js处调用:

this.context.router.history.push({ pathname : '/editUser' ,query : { id: ' admin'} });

取值方式:

在页面中,通过

const {id} = this.props.location.query;

或者

const id = this.props.location.query.id;

取值。

  缺点:这样用必须由其他页面跳过来,参数才会被传递过来,如果直接刷新,参数是传不过来的。所以后面放弃使用这样的方式,个人感觉对页面刷新不友好。

  优点:不需要配置路由表。路由表中的内容只需要写:<Route path='/editUser' component={EditUser}></Route>

3.通过state传参:

在路由中配置:

 <Route path=' /editUser '   component={EditUser}></Route>

使用时在link处配置:

 <Link to={{ path : ' /editUser' , state: { id: 'admin' }}}>编辑用户</Link>          

或者使用时在js处调用:

this.context.router.history.push({ pathname : '/editUser' ,state: { id: ' admin'} });

取值方式:

在页面中,通过

const {id} = this.props.location.state;

或者

const id = this.props.location.state.id;

取值。

  缺点:同query。

  优点:同query ,且优于query的是,他传递的参数在地址栏是加密的,而query在地址栏是不加密的

可选参数匹配

有时,我们的参数并不是一定需要的,这时,就可以用到可选参数匹配

react-router 2.0中可选参数写法:

<Route path="/system/editUser(/:id)" component={EditUser}/>

react-router 4.0中可选参数写法:

<Route path="/system/editUser/:id?" component={EditUser}/>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值