[英]Routes React Router Dom
我有這樣的路線:
export enum routes {
PROFILE_SETTINGS = "/settings/profile",
ACCOUNT_SETTINGS = "/settings/account",
PASSWORD_CHANGE = "/settings/account/password",
ACCOUNT_DELETE = "/settings/account/delete",
EMAIL_CHANGE = "/settings/account/email",
USER_COMMENTS = "/profile/:user/comments",
USER_PRODUCTS = "/profile/:user/products",
}
<BrowserRouter>
<ThemeProvider theme={theme}>
<CommunicatorTemplate>
<MainTemplate>
<Switch>
<ProfileTemplate>
<Route
exact
path={routes.USER_COMMENTS}
component={UserComments}
/>
<Route
exact
path={routes.USER_PRODUCTS}
component={UserProducts}
/>
</ProfileTemplate>
<SettingsTemplate>
<Route
exact
path={routes.PROFILE_SETTINGS}
component={ProfileSettings}
/>
<Route
exact
path={routes.ACCOUNT_SETTINGS}
component={AccountSettings}
/>
<Route
path={routes.PASSWORD_CHANGE}
component={PasswordChange}
/>
<Route path={routes.EMAIL_CHANGE} component={EmailChange} />
<Route path={routes.ACCOUNT_DELETE} component={AccountDelete} />
</SettingsTemplate>
</Switch>
</MainTemplate>
</CommunicatorTemplate>
</ThemeProvider>
</BrowserRouter>
問題是,當我 go 到任何以/settings
開頭的頁面時,我被重定向到Profile
頁面而不是 fe PROFILE_SETTINGS
或ACCOUNT_SETTINGS
。 我認為問題出在/settings/profile
因為它也有/profile
部分,但我該如何解決呢?
從Route
中刪除確切的內容。 所以
<Route
path={routes.PROFILE_SETTINGS}
component={ProfileSettings}
/>
問題是在Switch
組件中,只有Route
或Redirect
組件是有效的子組件。 回想一下, Switch
組件會渲染與位置匹配的第一個子<Route>
或<Redirect>
,但您已將路由包裝在ProfileTemplate
或SettingsTemplate
中,因此,只有ProfileTemplate
被“匹配”並被渲染。 包裝器內的包裝路線現在只是包含性地匹配和渲染,就像Switch
根本不存在一樣。
將包裝器包裝在匹配的路由中,然后將路由包裝在Switch
中,以便它們完全匹配。
<BrowserRouter>
<ThemeProvider theme={theme}>
<CommunicatorTemplate>
<MainTemplate>
<Switch>
<Route path={[routes.USER_COMMENTS, routes.USER_PRODUCTS]}>
<ProfileTemplate>
<Switch>
<Route
exact
path={routes.USER_COMMENTS}
component={UserComments}
/>
<Route
exact
path={routes.USER_PRODUCTS}
component={UserProducts}
/>
</Switch>
</ProfileTemplate>
</Route>
<Route
path={[
routes.PROFILE_SETTINGS,
routes.ACCOUNT_SETTINGS,
routes.PASSWORD_CHANGE,
routes.EMAIL_CHANGE,
routes.ACCOUNT_DELETE
]}
>
<SettingsTemplate>
<Switch>
<Route
exact
path={routes.PROFILE_SETTINGS}
component={ProfileSettings}
/>
<Route
exact
path={routes.ACCOUNT_SETTINGS}
component={AccountSettings}
/>
<Route
path={routes.PASSWORD_CHANGE}
component={PasswordChange}
/>
<Route path={routes.EMAIL_CHANGE} component={EmailChange} />
<Route path={routes.ACCOUNT_DELETE} component={AccountDelete} />
</Switch>
</SettingsTemplate>
</Route>
</Switch>
</MainTemplate>
</CommunicatorTemplate>
</ThemeProvider>
</BrowserRouter>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.