0

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

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

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

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

4

1 回答 1

0

看来您正在寻找嵌套路由

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

<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 被修改为附加到之前的内容。

type要处理可选参数,您必须以product某种方式区分 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

这样你就可以在语句中添加Route上面的 forcatalogSwitch

于 2018-12-29T19:59:37.060 回答