React three routing parameters
1. Params passing parameters
Advantages: Refresh the address bar and the parameters still exist
Disadvantages: Only strings can be passed, and if too many values are passed, the URL will become long and ugly.
// 路由页面:
<Route path='/home/message/detail/:id/:title' component={
Detail}/> //注意要配置 /:id
//路由跳转并传递参数:
//链接方式:
<Link to={
`/home/message/detail/${
id}/${
title}`}>{
title}</Link>
//或:
<Link to={
{
pathname:`/home/message/detail/${
id}/${
title}`}}>{
title}</Link>
//js方式:
this.props.history.push(`/home/message/detail/${
id}/${
title}`)
// 或:
this.props.history.push({
pathname:`/home/message/detail/${
id}/${
title}`})
//获取参数:
const {
id,title} = this.props.match.params //注意这里是match而非history
2. Passing parameters between query and state
Advantages: Parameter passing is elegant, and objects can be passed when passing parameters; however, the state parameter passing method only supports Browserrouter routing, not hashrouter.
Disadvantages: Refresh the address bar, parameters are lost
- 2.1. Query parameter passing
//路由页面:
<Route path="/home/message/detail" component={
Detail}/> //无需配置
//路由跳转并传递参数:
// 链接方式:
<Link to={
{
pathname: '/home/message/detail',
query: {
id:id, title: title}
}}>{
title}</Link>
//js方式:
this.props.history.push({
pathname: '/home/message/detail',
query: {
id, title}
})
//获取参数:
const {
id, title} = this.props.location.query ||{
}
- 2.2. State parameter passing
//路由页面:
<Route path="/home/message/detail" component={
Detail}/> //无需配置
//路由跳转并传递参数:
// 链接方式:
<Link to={
{
pathname: '/home/message/detail',
state: {
id:id, title: title}
}}>{
title}</Link>
//js方式:
this.props.history.push({
pathname: '/home/message/detail',
state: {
id, title}
})
//获取参数:
const {
id, title} = this.props.location.state ||{
}
###3. Search parameters
Advantages: Refresh the address bar and the parameters still exist
Disadvantages: Only strings can be passed, and if too many values are passed, the URL will become long and ugly.
//路由页面:
<Route path='/home/message/detail' component={
Detail}/>
//路由跳转并传递参数:
// 链接方式:
<Link to={
`/home/message/detail/?id=${
id}&title=${
title}`}>{
title}</Link>//无需配置
//js方式:
this.props.history.replace(`/home/message/detail/?id=${
id}&title=${
title}`)
//获取参数:
const {
search} = this.props.location
const {
id, title} = qs.parse(search.slice(1)) //slice去掉前面的'?'