- 携带params参数
{/* 路由传递params参数 */}
<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
{/* 路由跳转 注意这里是element不是component */}
<Routes>
<Route path='/detail/:id/:title' element={<Details/>}/>
</Routes>
{/*Detail组件中 */}
import React from 'react'
import { useParams } from "react-router-dom";
export default function Detail() {
const mockData=[
{id:'001',content:'我爱你中国'},
{id:'002',content:'我爱你家乡'},
{id:'003',content:'我爱你长江'}
]
const params = useParams(); // 获取动态路由的值
const {id,title} = params;
const newData=mockData.find((detailObj)=>{return detailObj.id===id})
return (
<ul>
<li>ID:{newData.id}</li>
<li>TITLE:{title}</li>
<li>MESSAGE:{newData.content}</li>
</ul>
)
}
2.传递search参数
{/* 传递search参数 */}
<Link to={`/home/message/detail?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>
{/* 注册路由,如果携带的是search参数时,无需声明接收,直接注册就好*/}
<Routes>
<Route path='/detail' element={<Details/>}/>
</Routes>
{/*Detail组件中 */}
import {useSearchParams} from "react-router-dom";
export default function Detail() {
const mockData=[
{id:'001',content:'我爱你中国'},
{id:'002',content:'我爱你家乡'},
{id:'003',content:'我爱你长江'}
]
const [searchParams] = useSearchParams(); // 获取查询字符串的值
const id = searchParams.get('id')
const title = searchParams.get('title')
// console.log(id,title)
const newData=mockData.find((detailObj)=>{return detailObj.id===id})
// console.log(newData)
return (
<ul>
<li>ID:{newData.id}</li>
<li>TITLE:{title}</li>
<li>MESSAGE:{newData.content}</li>
</ul>
)
}
- 传递state参数(有待考证)
{/* 传递state参数 */}
<Link to={{pathname:"/home/message/detail",state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link>
{/* 注册路由,如果携带的是state参数时,无需声明接收,直接注册就好*/}
<Routes>
<Route path='/detail' element={<Details/>}/>
</Routes>
{/*Detail组件中 */}
import React from "react";
import {useLocation} from "react-router-dom";
export default function Detail() {
const mockData=[
{id:'001',content:'我爱你中国'},
{id:'002',content:'我爱你家乡'},
{id:'003',content:'我爱你长江'}
]
const location = useLocation(); // 获取上一个页面传递进来的 state 参数
// console.log(location.state)
const {state:{id,title}} = location
const newData=mockData.find((detailObj)=>{return detailObj.id===id})
// console.log(id,title)
return (
<ul>
<li>ID:{newData.id}</li>
<li>TITLE:{title}</li>
<li>MESSAGE:{newData.content}</li>
</ul>
)
}