路由传参!!
一般分为三种传参方式
1.通过params
是通过在路由后面写/:id将路径配合?name=xxx的形式
通过useParams来获取路径参数
<Route path='/route/:id' component={Route}></Route>
// 声明式跳转
<Link to={`/route/${id}`}></Link>
// 编程式跳转
history.push(`/route/${id}`)
// 获取参数
const params = useParams()
console.log(params.id)
2.通过query 通过在跳转时写入search将参数以字符串带过去
通过location来获取参数
// 不需要配置路由
<Route path='/route/' component={Route}></Route>
// 声明式跳转
<Link to={{pathname:'/route', search: { id: '1'}}}></Link>
// 编程式跳转
history.push({pathname:'/route', search: '1'})
// 获取参数
const location = useLocation<{id:any}>()
console.log(location.state.id) // ?1
// 去除 ?
const str = '?1'
str.split('?')[1] // 1
3.通过state 通过跳转的时候写入state将参数以对象的形式带过去
通过location来获取参数
// 跟 query 类似,query 传的参数会在地址栏上公开, state 不会公开
<Route path='/route/' component={Route}></Route>
// 声明式跳转
<Link to={{pathname:'/route', state: { id: '1'}}}></Link>
// 编程式跳转
history.push({pathname:'/route', state: { id: '1'}})
// 获取参数
const location = useLocation<{id:any}>()
console.log(location.state.id) // 1