React router-dom <Link> to pass multiple params and access them using useParams

僤鯓⒐⒋嵵緔 提交于 2021-01-29 05:35:32

问题


I use:

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

I am passing in multiple params like so:

<Link to={`/tech/${data.foo}${data.bar}`}>{data.you}</Link>

I try to access my params passed using useParams like this:

let { foo } = useParams<{foo:string}>();
let { bar } = useParams<{bar:string}>();

I can access foo, but bar says undefined if I console.log it. But if I do this:

<Link to={`/tech/${data.bar}/${data.foo}`}>{data.you}</Link>

I then have access to data.bar but not data._foo

<div>{foo}</div>
<div>{bar}</div>

Does anyone know how to properly write this so I can pass 2 params and access both of them using useParams like I am trying to do? Thanks!


回答1:


As you can see in this running example passing multiple parameters is possible as long as you define the Route properly.

<Route path="/page/:foo/:bar" component={Page} />

You must define a parameter for both pieces using the :.

Then accessing like const { foo, bar } = useParams(); will work. You may also keep them on separate lines like you had in your question, but this way is more concise.



来源:https://stackoverflow.com/questions/64894944/react-router-dom-link-to-pass-multiple-params-and-access-them-using-useparams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!