如何使用 React Router dom 将目录组件替换为详细的项目组件?
How to replace catalog component with detailed item component using react router dom?
我有一个主要组件,用于使用路由在我的主要组件之间切换。
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。我可以让 url 通过 match 道具将用户发送到,但是我应该为我的 DetailedView 组件的路径添加什么?
你好像在找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 被修改为附加到前面的内容。
要处理可选参数,您必须以某种方式区分 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
这样你就可以在 Switch
语句
中为 catalog
添加 Route
我有一个主要组件,用于使用路由在我的主要组件之间切换。
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。我可以让 url 通过 match 道具将用户发送到,但是我应该为我的 DetailedView 组件的路径添加什么?
你好像在找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 被修改为附加到前面的内容。
要处理可选参数,您必须以某种方式区分 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
这样你就可以在 Switch
语句
catalog
添加 Route