【问题标题】:How to replace catalog component with detailed item component using react router dom?如何使用react router dom将目录组件替换为详细的项目组件?
【发布时间】:2018-12-29 19:11:48
【问题描述】:

我有一个主要组件,用于使用路由在主要组件之间切换。

const Main = () => {
  return (
    <Switch>
      <Route path="/" exact component={Landing} />
      <Route
        path="/catalog/:category/:type?/:typeOption?"
        component={Catalog}
      />
      <Route path="???" component={DetailedView} />
      />
    </Switch>
  );
};

目录组件基本上是商店中可用商品的列表。当用户单击其中一个项目时,我想将 Catalog 组件替换为显示该项目及其所有详细信息的组件。当我在详细页面上时,url 应该是我所在的类别,并在其上附加了项目的名称。

例如 - 我可能在 /catalog/mens/shirts/brown 上,当我点击一个项目时,我会被发送到 - /catalog/mens/shirts/brown /nameOfShirt。我可以通过 match 属性获取将用户发送到的 url,但是我的DetailedView 组件的路径是什么?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    你好像在找Nested Routing

    在主组件内部,开关将只提供登陆和目录视图。

    <Switch>
      <Route path="/" exact component={Landing} />
      <Route
        path="/catalog/:category/:type?/:typeOption?"
        component={Catalog}
      />
    </Switch>
    

    现在,在目录视图的更深处,您可以使用以下内容嵌套详细信息:

    function Catalog({ match }) {
      return (
        <div>
          <Route
            path={match.path + '/:nameOfProduct'}
            component={DetailedView}
          />
          <Route
            exact
            path={match.path}
            render={() => <h3>Render the list of items here</h3>}
          />
        </div>
      )
    }
    

    这样,URL 被修改为附加到之前的内容。

    要处理可选参数,您必须以某种方式区分typeproduct 的ID。例如。如果我有一个限制,即所有产品 ID 都以 pr 开头,那就是:

    <Switch>
      <Route path={`${match.path}/:id(pr.*)`} render={() => <p>Product</p>} />
      <Route path={match.path} render={() => <p>Still Catalogue</p>} />
    </Switch>
    

    如果您无法使用正则表达式模式区分它们,那么您必须在 URL 中添加一个路由参数,使其:

    /catalog/mens/shirts/product/nameOfShirt /catalog/mens/shirts/type/product/nameOfShirt

    这样,您可以在Switch 语句中将Route 添加到catalog 的上方

    【讨论】:

    • 嵌套路由绝对是我想要的。但是一个问题是我在目录路由中的最后两个参数是可选的。因此,只要 /catalog/:category/ 之后有内容,它就会尝试显示详细视图。我怎么知道什么时候应该显示项目列表以及什么时候应该显示详细视图。
    猜你喜欢
    • 2018-06-05
    • 2020-03-30
    • 1970-01-01
    • 2020-08-30
    • 2015-07-26
    • 2020-09-27
    • 2020-01-13
    • 2017-09-14
    • 2019-07-11
    相关资源
    最近更新 更多