乐趣区

关于前端:React-reactrouterdom-v6路由传参

共有三种形式:
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 + 拼接 search
const 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…

退出移动版