likes
comments
collection
share

[React] react-router-dom v6路由传参

作者站长头像
站长
· 阅读数 22

共有三种方式:1、search传参2、params传参3、state传参

1、search传参 (query格式, ? + &)

传参页

import { useNavigate, createSearchParams} from "react-router-dom";

参数的放入有3种方式1.1 直接拼接const Pages = () => { const navigate = useNavigate(); const id = "1"; const grade = "2"; const goTo = () => {

  navigate(`/class?id=${id}&grade=${grade}`)

}}

1.2 pathname + 拼接searchconst Pages = () => { const navigate = useNavigate(); const id = "1"; const grade = "2"; const goTo = () => {

  navigate({
    pathname: "/class",
    search: `?id=${id}&grade=${grade}`
})

}}

1.3 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>)}}

后文会省略各种不必要代码,保留关键部分

2、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, grade } = useParams(); return (<h1>id : {id}, grade : {grade}</h1>)}}

3、state传参

传参页

import { useNavigate } from "react-router-dom";const goTo = () => { navigate(/class, { state: {id, grade} } )}

接收页

import { useLocation } from "react-router-dom";

const ToPages = () => { const location = useLocation (); const { id, grade } = location.state; return (<h1>id : {id}, grade : {grade}</h1>)}}

注意:1、const params = { id: '1', grade: '2' };createSearchParams(params)这里的key对应的value在ts中要求为string。2、state的传参不要求value为string。3、search传参和params传参,参数出现在url中,刷新页面不会丢失。而state传参不通过url刷新页面会丢失参数。

完结

同步更新到自己的语雀https://www.yuque.com/diracke...

转载自:https://segmentfault.com/a/1190000042309247
评论
请登录