问题描述
我使用:
import { Link } from react-router-dom";
我像这样传入多个参数:
<Link to={`/tech/${data.foo}${data.bar}`}>{data.you}</Link>
我尝试像这样访问使用 useParams 传递的参数:
let { foo } = useParams();let { bar } = useParams();
我可以访问 foo,但是如果我使用 console.log,bar 会显示 undefined.但如果我这样做:
<Link to={`/tech/${data.bar}/${data.foo}`}>{data.you}</Link>
然后我可以访问 data.bar 但不能访问 data._foo
{foo}<div>{bar}</div>
有谁知道如何正确编写它,以便我可以传递 2 个参数并像我尝试使用的那样使用 useParams 访问它们?谢谢!
正如你在这个运行示例 传递多个参数是可能的,只要您正确定义了Route
.
您必须使用 :
为两个部分定义一个参数.
然后像 const { foo, bar } = useParams();
这样的访问将起作用.您也可以像在问题中一样将它们放在不同的行上,但这种方式更简洁.
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!
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.
这篇关于React router-dom <Link>传递多个参数并使用 useParams 访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!