前提:
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}/>

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

被折叠的 条评论
为什么被折叠?



