React-路由传参数
一. 路由传参方法;
二. 路由跳转模式;
三. 编程式路由导航;
1. 方式1 ---- params参数
页面1
1.传参;
<Link to="/nav1/id/title" />
or动态的模板字符串
<Link to={`/nav1/${id}/title`} />
2.声明 ---- 接受params参数
<Route path="/nav1/:id/:title">
详情页
3.接收 ---- 他们都是以组件的形式传参, 可以用props接受参数
let {id, title} = this.props.match.params
2. 方式2 ---- search参数
search 无需声明接收
1.传参
<Link to={`/nav1?id=${id}&title='这是标题'`} />
2. 无需声明
<Route path="/nav1"/>
3. 接收
this.props.location.search
const { search } = this.props.location.search
console.log(qs.parse(search.slice(1))) // search.slice(1)为了处理?id中的?
引入qs 这个react自带的, qs可以转换 ?id=123&title="asdf'这个格式
import qs from 'querystring'
qs.stringify(obj)
qs.parse(str)
3. 方式3 ---- state参数
state无需声明接收
1.传参
<Link to={{pathname: 'nav1', state: {id: id, title: ''}}} />
2.无需声明
3.接收
this.props.location.state || {}
这个意思是如果 this.props.location.state 有值 就用这个 没有就是 {}
用state的时候 如果清除了浏览缓存就会报错, 那么就可以用上面的办法
二.路由跳转模式
push 和 repalce
模式是push
下面是replace
<Link replace={true} />
三.编程式路由导航
<button onClick={() => this.linkFun(id, title)}></button>
linkFun = (id, tile) => {
// replace + 携带params参数
this.props.history.replace(`/nav/${id}/${title}`)
this.props.history.push(`/nav/${id}/${title}`)
// search
this.props.history.push(`/nav/?id=${id}&title=${title}`)
// state
this.props.history.push(`/nav`, {id, title})
}
总结:
<Router>
<link></link>
// 接收路由参数
<Route></Route>
</Router>