[React] react-router-dom 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 (

id : {id}, grade : {grade}

)}
}

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

2、params传参 (restful格式),需要在Route上显示写明 :params

路由部分


  } />


传参页

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 (

id : {id}, grade : {grade}

)}
}

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 (

id : {id}, grade : {grade}

)}
}

注意:
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...

你可能感兴趣的:(前端react.js路由传参)