react-router v4 参数传递

react-router v4 参数传递有3中方式,分别是params,query 和 state。

1. params(路径参数)

parrams的传递要在路由配置上添加参数,是路由路径的一部分,在斜杠后面写参数,就是路径参数。

//路由表
<Route path='/user/:id ' component={User}></Route>
//Link方式
<Link to={ pathname:' /user/2 '}>XXXX</Link>   
//js方式
this.props.history.push( { pathname:' /user/2 '})
//接收
this.props.match.params.id

2. search(查询字符串)

无需修改路由表,直接带参数即可,需要encode。

//Link方式
<Link to={pathname:' /user',query:{name:'meimei'}}>
//js方式
this.props.history.push({ pathname:' /user',query:{name:'meimei'}})
//接收方式
this.props.location.query.name //meimei

3. state

无需修改路由表,直接传递。

//Link方式
<Link to={{ pathname:' /user', state:{value:123}}}> 
//js方式
this.props.history.push({ pathname:' /user', state:{value:123}})
//接收方式
this.props.location.state.value

4. hash或自定义参数

//Link方式
<Link to={{ pathname:' /user',hash:'#hashvalue',abc:'def'}}>
//js方式
this.props.history.push({ pathname:' /user', hash:'#hashvalue',abc:'def'})
//接收方式
this.props.location.hash  //#hashvalue
this.props.location.abc  //def  (自定义参数)

猜你喜欢

转载自www.cnblogs.com/mengff/p/12639399.html