目录
参数放入的方式
一、直接拼接
const Pages = () => {
const navigate = useNavigate();
const id = "1";
const grade = "2";
const goTo = () => {
navigate(`/class?id=${id}&grade=${grade}`)
}
}
二、pathname + 拼接search
const Pages = () => {
const navigate = useNavigate();
const id = "1";
const grade = "2";
const goTo = () => {
navigate({
pathname: "/class",
search: `?id=${id}&grade=${grade}`
})
}
}
三、pathname + 创建search
const Pages = () => {
const navigate = useNavigate();
const params = { id: '1', grade: '2' };
const goTo = () => {
navigate({
pathname: "/class",
search: `?${createSearchParams(params)}`
})
}
}
四、页面接收参数
import { useSearchParams } from "react-router-dom";
const toPages = () => {
const [searchParams] = useSearchParams()
const id = searchParams.get("id")
const grade = searchParams.get("grade")
return (<h1>id: {id}, grade: {grade}</h1>)
}
params 传参
restful 格式 需要在Route 上显示写明 :params
<BrowserRouter>
<Routes>
<Route path={'/class/:id/:grade'} element={<ToPage/>} />
</Routes>
</BrowserRouter>
传参页面
import { useNavigate } from "react-router-dom";
const goTo = () => {
navigate(`/class/${id}/${grade}`)
}
接收页面
import { useParams } from "react-router-dom";
const ToPages = () => {
const { id, params } = useParams()
return (<h1>id : {id}, grade : {grade}</h1>)
}
state 传参
传参页
import { useNavigate } from "react-router-dom";
const goTo = ()=> {
navigate(`/class`, { state: {id, grade} } )
}
接收页
import {useLocation } from "react-router-dom"
const ToPage = () => {
const location = useLocation()
const {id, grade} = location.state
}
注意:
1、const params = { id: '1', grade: '2' };
createSearchParams(params)
这里的key对应的value在ts中要求为string。
2、state的传参不要求value为string。
3、search传参和params传参,参数出现在url中,刷新页面不会丢失。而state传参不通过url刷新页面会丢失参数。