reactjs - 从 url 查询中获取 URL 参数
问题描述
目标:从 URL 中检索 ID
我有一个包含以下代码的产品提要:
<Router>
<Header />
<Switch>
<Route exact path="/" component={Feed} />
<Route exact path="/" />
<Route
exact
path="/product/:productId"
component={DetailProductPage}
/>
</Switch>
</Router>
这是我的提要代码:
<div className="feed">
<div className="feed__cards">
{products.map((product) => (
<ProductCard
image={product.image}
brand={product.brand}
name={product.name}
id={product.id}
/>
))}
</div>
</div>
以及创建 URL的ProductCard
组件:
<div className="productCard__container">
<img src={image} />
<h1>{brand}</h1>
<h2>{name}</h2>
<p>{id}</p>
<p>{<a href={`/product/${id}`}>View</a>}</p>
</div>
当我点击单个产品时,我被重定向到单个产品页面:
function DetailProductPage({ id }) {
const productId = { id };
return (
<div>
<h1>Product page</h1>
<p>{id}</p>
</div>
);
}
当我走这条路时,我得到一个带有产品参数的 URL:(例如,http://localhost:3000/product/6CeJGSm7dBTABs8rRBJh
)
如何查询6CeJGSm7dBTABs8rRBJh
URL 的一部分并将其放入变量中?
解决方案
我假设您为此使用 react-router-dom。有几种方法可以从 URL 中检索此值,但使用提供的代码的最简单方法是使用useParams
钩子,如下所示:
import { useParams } from 'react-router-dom';
function DetailProductPage({ id }) {
const { productId } = useParams();
return (
<div>
<h1>Product page</h1>
<p>{productId}</p>
</div>
);
}
推荐阅读
- excel - 我尝试在 Excel 中通过 VBA 创建一个微调按钮,但它给了我一个“自动化错误,灾难性故障”?
- java - 接收需要通过递归构建字符串的方法的 OutOfBounds,不知道为什么
- azure - 有没有一种在 Azure 中的应用程序之间共享配置的好方法?
- ruby-on-rails - 导轨/设计。在 sign_in 过程中包含验证码响应参数
- java - 了解 Spring Boot 2 的默认 logback 配置
- oracle - 将总金额转换为单词
- python - 如何改进评估列表以确定它是否包含特定连续项目的方法?
- react-native - expo cli 和 ADB 错误:无法连接到守护进程
- ruby-on-rails - 如何为 ActiveRecord 模型定义 rescue_from-type 处理程序?
- mongodb - 错误:密码包含非法的未转义字符