【问题标题】:How to use useParams() with nested route如何在嵌套路由中使用 useParams()
【发布时间】:2021-11-14 14:48:42
【问题描述】:

如何在嵌套路由中使用 URL 参数?

您好,我想建立一个显示单个产品的电子商务页面。

所以,我使用useParams() 从 URL 中提取道具并使用filter() 呈现单个项目。

但是第 3 方 API 会返回一个带有斜线符号的 ID。

例如

{
  [
    id: 'electronics/2020/product1'
  ],
  [
    id: 'sportwear/product2'
  ]
}

当我从useParams() 获取数据时,它只会返回electronicssportwear。不是整个 ID

如何使用 React Router DOM 获取整个 ID

附:我错过了什么吗?我必须使用useRouthMatch() 吗?


我的文件

// Route
<Route path="/view/:id" component={SingleProduct} />

// Link from map()

state.map(product => <Link to={product.id}>{product.title}</Link>);

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    据我所知,您没有任何嵌套路由,并且有几个选项。

    选项 1

    id 字段转换为无法解析为路由路径段的字符串。使用String.prototype.replaceAll 将所有"/" 替换为其他一些标记字符,例如"_"

    state.map(product => (
      <Link to={product.id.replaceAll("/", "_")}>
        {product.title}
      </Link>
    ));
    

    您可以稍后在标记字符上拆分字符串。

    例子:

    const { id } = useParams();
    
    • const [section, year, product] = id.split("_"); // 'electronics/2020/product1'
      
    • const [section, product] = id.split("_");       // 'sportwear/product2'
      

    选项 2

    明确声明所有类别的路线。请记住在 Switch 组件中按从更具体到最不具体的路线排序。

    例子:

    <Route
      exact
      path={[
        "/view/:section/:year/:productId", // '/view/electronics/2020/product1'
        "/view/:section/:productId"        // '/view/sportwear/product2'
      ]}
      component={SingleProduct}
    />
    

    SingleProduct 组件中访问路由的匹配参数。

    const { section, year, productId } = useParams();
    

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 2016-07-09
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多