一、params参数(传递的参数显示在url地址)
<Link to={`/home/message/detail/${item.id}/${item.title}`}>{item.title}</Link>
<Route path="/home/message/detail/:id/:title" component={Detail}/>
const {id,title} = this.props.match.params
二、search参数(传递的参数显示在url地址)。也可以叫query参数
<Link to={`/home/message/detail/?id=${item.id}&title=${item.title}`}>{item.title}</Link>
<Route path="/home/message/detail" component={Detail}/>
import queryString from 'query-string';
const {search} = this.props.location
const {id,title}=queryString.parse(search)
三、state参数(传递的参数不在url地址显示,刷新也可以保留住参数)
<Link to={{pathname:'/home/message/detail',state:{id:item.id,title:item.title}}}>{item.title}</Link>
<Route path="/home/message/detail" component={Detail}/>
const {id,title} = this.props.location.state
总结: 测试组件代码: 路由链接 与 路由注册 组件
import React, { Component } from 'react'
import { Link, Route } from 'react-router-dom'
import Detail from './Detail'
export default class Message extends Component {
state = {
messageArr: [
{ id: '01', title: '消息1' },
{ id: '02', title: '消息2' },
{ id: '03', title: '消息3' }
]
}
render() {
return (
<div>
<ul>
{this.state.messageArr.map((item) => {
return (
<li key={item.id}>
{}
{}
{}
{}
{}
{}
<Link to={{pathname:'/home/message/detail',state:{id:item.id,title:item.title}}}>{item.title}</Link>
</li>
)
})}
</ul>
<hr/>
{}
{}
{}
{}
{}
{}
<Route path="/home/message/detail" component={Detail}/>
</div>
)
接收参数 组件
import React, { Component } from 'react'
import queryString from 'query-string';
const detailObj = [
{id:'01',value:'我爱你中国'},
{id:'02',value:'我爱你 努力的自己'},
{id:'03',value:'我爱你 更好的自己'}
]
export default class Detail extends Component {
render() {
const {id,title} = this.props.location.state
const resultObj = detailObj.find((item)=>
item.id === id
)
return (
<div>
<ul>
<li>ID:{id}</li>
<li>TITLE:{title}</li>
<li>CONTENT:{resultObj.value}</li>
</ul>
</div>
)
}
}
|