state = {
msgData: [
{id: '01', title: '标题1'},
{id: '02', title: '标题2'}
]
}
传递 params 参数
{
msgData.map((msgObj) => {
<div key={msgObj.id}>
{/* 向路由组件传递 params 参数 */}
<Link to={`/home/msg/${msgObj.id}/${msgObj.title}`}>{msgObj.text}</Link>
</div>
})
}
{/* 声明接收 params 参数 */}
<Route path='/home/msg/:id/:title' component={Detail}>
{/* detail页面 */}
import React, { Component } from 'react'
const DetailData: [
{id: '01', content: '内容1'},
{id: '02', content: '内容2'}
]
export default class Detail extends Component {
render() {
// 接收 params 参数
const {id, title} = this.props.match.params
const findResult = DetailData.find((detailObj) => {
return detailObj.id === id
})
return (
<ul>
<li>ID:{id}</li>
<li>TITLE:{title}</li>
<li>CONTENT:{findResult.content}</li>
</ul>
)
}
}
说明:
- 路由链接(携带参数):
<Link to='/demo/test/tom/18'>详情</Link>
- 注册路由(声明接收):
<Route path=/demo/test/:name/:age' component={Test}>
- 接收参数:
const {name, age} = this.props.match.params
传递 search 参数
/* 向路由组件传递 search 参数 */
<Link to={`/home/msg/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.text}</Link>
引入 querystring 库
import qs from 'querystring'
// stringify()方法可以将 json对象转换为urlencoded编码字符串
let obj = {name: 'tom', age: 18}
console.log(qs.stringify(obj)) // name=tom&age=18
// parse()方法可以将 urlencoded编码字符串转换为json对象
let str= 'name=tom&age=18'
console.log(qs.parse(str)) // {name: 'tom', age: 18}
{/* detail页面 */}
// 接收 search 参数
const { search } = this.props.location
const {id, title} = qs.parse(search.slice(1))
说明:
- 路由链接(携带参数):
<Link to='/demo/test/?name=tom&age=18'>详情</Link>
- 注册路由(无需声明,正常注册即可):
<Route path=/demo/test' component={Test}>
- 接收参数:
const search = this.props.location.search
备注:获取到的search
是urlencoded
编码字符串,需要借助querystring
解析
传递 state 参数
/* 向路由组件传递 state 参数 */
<Link to={{pathname:'/home/msg', state:{id: msgObj.id, title:msgObj.title }}}>{msgObj.text}</Link>
{/* detail页面 */}
import React, { Component } from 'react'
const DetailData: [
{id: '01', content: '内容1'},
{id: '02', content: '内容2'}
]
export default class Detail extends Component {
render() {
// 接收 state 参数
// 防止清除缓存后报错
const {id, title} = this.props.location.state || {}
const findResult = DetailData.find((detailObj) => {
return detailObj.id === id
}) || {}
return (
<ul>
<li>ID:{id}</li>
<li>TITLE:{title}</li>
<li>CONTENT:{findResult.content}</li>
</ul>
)
}
}
说明:
- 路由链接(携带参数):
<Link to={{path: '/demp/test', state: {name: 'tom', age: 18}}}>详情</Link>
- 注册路由(无需声明,正常注册即可):
<Route path=/demo/test' component={Test}>
- 接收参数:
this.props.location.state
备注:地址栏没有参数,但是刷新也可以保留住参数,但是清除缓存后就没有参数