[英]Trying to add a detail product component. React-router
I have a component products
which lists every product in the /Products
url.我有一个组件
products
,其中列出了/Products
url 中的每个产品。 I'm trying to make another component Detail
that displays specific product
in the browser.我正在尝试制作另一个在浏览器中显示特定
product
的组件Detail
。 This is the URL I've been trying to create Detail/{some id goes here}
.这是 URL 我一直在尝试创建
Detail/{some id goes here}
。 The problem is how am i going to know which product
clicked, so how am I supposed to show this specific product
in the Detail
component.问题是我怎么知道点击了哪个
product
,那么我应该如何在Detail
组件中显示这个特定的product
。 I do have a Detail
and Products
component.我确实有一个
Detail
和Products
组件。
My router is below:我的路由器如下:
<Router>
<NavbarComponent></NavbarComponent>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/home">
<Home />
</Route>
<Route exact path="/Products">
<Products />
</Route>
<Route exact path="/Detail/:int">
<Detail />
</Route>
</Switch>
</Router>
I'm not going to share my Products
component since It's composed 200 lines of code.我不会分享我的
Products
组件,因为它由 200 行代码组成。 I'm just gonna share the search svg
in my Products
that I want it to take me to the Detail/{id}
page when I click.我只是要在我的
Products
中分享搜索svg
,我希望它在我单击时将我带到Detail/{id}
页面。
{filtered.map((product, index) => {
return (
<div key={index}>
<div className="card shadow" style={{ width: "18rem" }}>
<img
className="card-img-top"
src="https://dl.airtable.com/.attachmentThumbnails/65708b701baa3a84883ad48301624b44/2de058af"
alt="Card image cap"
/>
<Link className="link" to={"Detail",index}>
<svg
stroke="currentColor"
fill="white"
stroke-width="0"
viewBox="0 0 512 512"
height="1em"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
</svg>
</Link>
This is what you will need - https://reactrouter.com/web/example/url-params/这就是您需要的 - https://reactrouter.com/web/example/url-params/
In summary, the :int
can be availed in the Detail
component as const {int} = useParams();
总之,
:int
可以在Detail
组件中作为const {int} = useParams();
. . And while handling the click in the
Products
component, you will have to pass the product-id as /Details/{productId}
using the Link
component.在处理
Products
组件中的点击时,您必须使用Link
组件将 product-id 作为/Details/{productId}
传递。
In this manner once the Link
is clicked to bring the route to Detail/xyz-product-id
, the Detail
component will render having that xyz-product-id
available as int
in the code.以这种方式,一旦单击
Link
以将路由带到Detail/xyz-product-id
, Detail
组件将呈现该xyz-product-id
作为代码中的int
可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.