react 18 react-router-dom V6 路由传参的几种方式
路由配置如下
label:"首页",
meta:{
title:"首页"
}
},
{
path: '/',
// <AutnToken><Layout></Layout></AutnToken>
element:<Layout></Layout>,
label:"首页",
meta:{
title:"首页"
},
children:[
{
path:'/home',
element:withLoading(<Home></Home>),
label:"首页",
meta:{
title:"首页"
}
},
{
path:'/chargingStation',
element:withLoading(<ChargManage></ChargManage>),
label:"充电站管理",
meta:{
title:"充电站管理"
},
children:[
{
path:'/chargingStation/list',
element:withLoading(<ChargMangeList></ChargMangeList>),
label:"充电站列表",
meta:{
title:"充电站列表"
}
},
{
path:'/chargingStation/addCharginns',
element:withLoading(<AddChargingStation></AddChargingStation>),
label:"添加充电站",
},
{
path:'/chargingStation/chargingPile',
element:withLoading(<Citytree></Citytree>),
label:"充电桩列表",
meta:{
title:"充电桩列表"
}
}
]
},
{
path:'/systemSet',
element:withLoading(<Systemset></Systemset>),
label:"设置",
meta:{
title:"设置"
},
children:[
{
path:'/systemSet/list/:id?',
element:withLoading(<Citytree></Citytree>),
label:"区域管理",
meta:{
title:"区域管理"
}
}
]
}
]
},
{
path: '/login',
element:<Login></Login>,
label:"登录"
},
{
path: '*',
element:<Page404></Page404>,
label:"404"
},
]
编程式路由跳转后传参
跳转的几种方式
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/chargingStation/addCharginns');
navigate('/chargingStation/addCharginns', { replace: true });
navigate({
pathname: '/chargingStation/addCharginns'
});
navigate({
pathname: '/chargingStation/addCharginns',
search: '?id=100&name=zhufeng'
});
navigate(`/systemSet/list/15`);
参数两种方式
问号传参
import qs from 'qs';
navigate({
pathname:'/chargingStation/addCharginns',
search:qs.stringfy({
id:100,
name:'zhufeng'
})
})
路由传参
navigate(`/systemSet/list/15`);
隐藏参数 也就是浏览器无法直接看到参数
navigate('/chargingStation/addCharginns', {
//历史记录池替换现有地址
replace: true,
//隐式传参信息
state: {
id: 100,
name: 'zhufeng'
}
});
获取路由中的参数
//获取问号传参信息
const location = useLocation();
// location.search:"?id=100&name=zhufeng"
const usp = new URLSearchParams(location.search);
console.log(usp.get('id'), usp.get('name'));
//获取问号传参信息
//useSearchParams返回结果是一个数组
//数组第一项是URLParamsSearch对象 第二个参数是修改的方法
let [usp] = useSearchParams();
console.log(usp.get('id'), usp.get('name'));
*/
//获取路径参数信息
const params = useParams();
console.log(params); //=>{id:100,name:'zhufeng'} */
//获取隐式传参信息
const location = useLocation();
console.log(location.state);