问题描述
我正在使用 react 路由器,并且创建了一个路径为 /account
的路由,该路由呈现 Account 组件。该组件呈现导航栏。在该导航栏下方,我希望它根据 URL 呈现不同的组件。如果 URL 是 account/edit
,我想显示编辑帐户组件,如果 URL 是 account/myorders
,我希望它显示我的订单组件,最后如果 URL 是 account/favorites
,我希望它显示在我的导航栏下方显示收藏夹组件,
- 编辑帐户
- 我的订单
- 收藏夹
现在我遇到了这个问题,即 url 发生了变化,但在我的导航栏下方没有任何组件呈现。如果我在 /account
路线上使用精确路径,我会在路线 /edit
、/myorders
和 /favorites
上得到“路径不存在”。如果我不在 /account
路线上使用精确,则所有路线上都会显示相同的视图。只有当我将组件更改为 /edit
到 /
时,才会出现这种情况。
function Routes() {
return (
<Switch>
<Route path="/" component={Home} exact />
<Route path="/account" component={Account} />
<Route render={() => <Route component={Error} />} />
</Switch>
);
}
这些是导入到我的 App.js 组件中的现有路由
const Account = () => {
return (
<Router>
<NavBar />
<Switch>
<Route path="/edit" component={Editaccount} exact />
<Route path="/myorders" component={MyOrders} />
<Route path="/favorites" component={Favorites} />
</Switch>
</Router>
);
};
这些是我的 Account.js 组件中不起作用的路由
解决方法
问题在于您使用 <Router></Router>
将 routes
包装在 Acouunt
组件中。
尝试删除它,像这样:-
const Account = () => {
return (
<NavBar />
<Switch>
<Route path="/edit" component={EditAccount} exact />
<Route path="/myorders" component={MyOrders} />
<Route path="/favorites" component={Favorites} />
</Switch>
);
};
Check this answer 了解更多信息。
,我的解决方案是使用这样的嵌套路由。
const Account = () => {
let match = useRouteMatch();
return (
<Router>
<NavBar />
<h1>Account</h1>
<Switch>
<Route path={`${match.path}/edit`} component={EditAccount} exact />
<Route path={`${match.path}/myorders`} component={MyOrders} />
<Route path={`${match.path}/favorites`} component={Favorites} />
</Switch>
</Router>
);
};