react-router:传参方式

2021-01-15  本文已影响0人  Melody_28a2
一、get传参

1.路由配置

<Route path='/user' component={User} />

2.路由跳转

#html
<Link to={'/user?name="melody"&id=3'}>点击跳转</Link>
<Link  to={{pathname: "/user",search: "?name=melody&id=3" }}/>
#js
this.props.history.push({
    pathname: "/user",
    search: "?name=yangjing&id=3",
  })

3.获取参数

//直接获取
this.props.location.search
//url模块来解析url地址    在react里面使用url模块需要安装url模块    cnpm install url --save
//获取get传值
var query=url.parse(this.props.location.search,true).query;
console.log(query)
二、params传参(动态路由)

特点:刷新页面参数不消失,参数会在地址栏显示

1.路由配置

<Route path='/about/:id' component={About} />

2.路由跳转

#html
<Link to={'/about/3'}>点击跳转</Link>
#js
this.props.history.push('/about/3')

3.获取参数

this.props.match.params.id  // 3
三、query传参

特点:刷新页面参数消失,参数不会在地址栏显示

1.路由配置

<Route path='/about' component={About} />

2.路由跳转

 //html:
<Link to={{pathname:'/about', query:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', query:{id:3}})

3.获取参数

this.props.location.query.id  // 3
四、state传参

特点:刷新页面参数不消失,参数不会在地址栏显示

1.路由配置

<Route path='/about' component={About} />

2.路由跳转

//html:
<Link to={{pathname:'/about', state:{id:3}}}>点击跳转</Link>
//js:
this.props.history.push({pathname:'/about', state:{id:3}})

3.获取参数

this.props.location.state.id  // 3
上一篇 下一篇

猜你喜欢

热点阅读