首页 > 解决方案 > 从 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

如何查询6CeJGSm7dBTABs8rRBJhURL 的一部分并将其放入变量中?

标签: reactjs

解决方案


我假设您为此使用 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>
  );
}

更多信息:https ://reactrouter.com/web/api/Hooks/useparams


推荐阅读