[我正在尝试使用React-Router 5.1和功能组件中的useParams挂钩在URL中传递多个参数。
但是我遇到了非常奇怪的行为。
我将网址粘贴到客户端中。
网址:
http://localhost:3000/onboarding/eventId=5e9a173f9166f800128c04d1&groupId=5e9a173f9166f800128c04dc&userId=5e9a173f9166f800128c04da
路径:
<Route path = '/onboarding/:eventId?/:groupId?/:userId?' exact component = {OnboardingViewController} />
[奇怪的东西#1:我必须将参数设置为可选,否则浏览器将永远挂起。
我使用所有这些策略将它们钓出:
var { eventId, groupId, userId } = useParams();
var { eventId } = useParams();
var { groupId } = useParams();
var { userId } = useParams();
奇怪的东西#2:不幸的是,当尝试使用这些参数时,会发生这种情况:
{userId: undefined, eventId: "eventId=5e9a173f9166f800128c04d1&groupId=5e9a173f9166f800128c04dc&userId=5e9a173f9166f800128c04da", groupId: undefined}
钩子仅获取第一个参数,然后将其余部分解释为te的一部分。
奇怪的东西#3:由于添加了此url params查询,访问页面Laoding的过程非常缓慢,需要几秒钟。
我没看到什么,做错了什么?
答案:
我做错了:
我正在使用url / eventId = 123。
这是错误的。
您只需要在URL url / 1/2/3中的正确位置提供资源,并告诉路由器这些东西将被称为eventId&groupId&userId。然后,您可以使用userPrams()钩访问组件中的那些。
谢谢大家!
您的路线结构和路线不匹配
如果您想在网址中使用参数,http://localhost:3000/onboarding/5e9a173f9166f800128c04d1/5e9a173f9166f800128c04dc/5e9a173f9166f800128c04da
您的Route组件将是:
<Route path = '/onboarding/:eventId/:groupId/:userId' exact component = {OnboardingViewController} />
然后您可以在OnboardingViewController
组件中使用它:
var { eventId, groupId, userId } = useParams();
console.log(eventId,groupId,userId)
您正在将匹配参数与URL查询参数混合在一起。
可以使用location
钩子从location
对象中检索URL查询参数。
给出URL useLocation
useLocation
虽然需要路线http://localhost:3000/onboarding/?eventId=5e9a173f9166f800128c04d1&groupId=5e9a173f9166f800128c04dc&userId=5e9a173f9166f800128c04da
您可以使用QueryParameter处理库,然后将它们转换为地图对象。
如果您可以通过以下形式对您的URL进行按摩:{
pathname: '/onboarding/',
search: '?eventId=5e9a173f9166f800128c04d1&groupId=5e9a173f9166f800128c04dc&userId=5e9a173f9166f800128c04da'
}
然后路由path="/onboarding/"
可以匹配http://localhost:3000/onboarding/5e9a173f9166f800128c04d1/5e9a173f9166f800128c04dc/5e9a173f9166f800128c04da返回的路径参数。
path='/onboarding/:eventId/:groupId/:userId'