4.React路由传参
class Message extends Component {
state = {
messageArr: [
{id: '01', title: '消息1'},
{id: '02', title: '消息2'},
{id: '03', title: '消息3'},
]
}
render() {
const {messageArr} = this.state
return (
<div>
<ul>
{
messageArr.map(msgObj => {
return (
<li key={msgObj.id}>
{/*向路由组件传递params参数*/}
{/*<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */}
{/*向路由组件传递search参数*/}
{/*<Link to={`/home/message/detail?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>*/}
{/*向路由组件传递state参数*/}
{/* 路由模式改成replace替换 , 默认为push堆栈 */}
<Link replace to={{pathname: '/home/message/detail', state:{id:msgObj.id, title: msgObj.title}}}>{msgObj.title}</Link>
</li>
)
})
}
</ul>
<hr/>
{/*声明接收params参数*/}
{/*<Route path='/home/message/detail/:id/:title' component={Detail}/>*/}
{/*search参数无需声明接收, 正常注册路由即可*/}
{/*<Route path='/home/message/detail' component={Detail}/>*/}
{/*state参数无需声明接收, 正常注册路由即可*/}
<Route path='/home/message/detail' component={Detail}/>
</div>
);
}
}
接收参数:
import React, {Component} from 'react';
// import qs from "querystring";
const detailData = [
{id:'01', title:'abc', content: '北京'},
{id:'02', title:'def', content: '上海'},
{id:'03', title:'ghi', content: '广州'},
]
class Detail extends Component {
render() {
console.log(this.props)
// 接收params参数
// const {id, title} = this.props.match.params
// 接收search参数
// const {search} = this.props.location
// const {id, title} = qs.parse(search.slice(1))
// 接收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>
);
}
}
export default Detail;