我有我所有的路由,作为一个很好的做法,我也有我的 NotFound 页面,我在我的 MainLayout 中添加了它,其中包含一个导航栏和一个页脚。但是我有一个问题,我的 NotFound 页面与其他路由的页面一起显示。
const Root = () =>
<BrowserRouter>
<Switch>
<ProtectedRoute exact path="/:username/contact-networks" component={ContactNetworks} />
<ProtectedRoute exact path="/:username/tags" component={UserTags} />
<ProtectedRoute exact path="/:username/profile-picture" component={UserProfilePicture} />
<MainLayout nofooter={['/login']}>
<Route exact path="/" component={Home} />
{!isAuthenticated ? (
<Fragment>
<Route exact path="/logup" component={Logup} />
<Route exact path="/login" component={Login} />
</Fragment>) : <Redirect to="/" />}
<Route exact path="/users/:username" component={UserProfile} />
<Route exact path="/:username/catalog/:product" component={ProductPage} />
<ProtectedRoute exact path="/:username/products/new" component={PostProduct} />
<Route exact path="/:username/opinions" component={ClientsOpinions} />
<ProtectedRoute exact path="/:username/opinions/new" component={NewOpinion} />
<Route exact path="/:shop/contact" component={ShopContact} />
<Route exact path="/search/results" component={SearchResults} />
<Route component={NotFound} />
</MainLayout>
</Switch>
</BrowserRouter >
答案 0 :(得分:0)
所有 Route
组件都需要是 Switch
的直接子代才能正常工作。每the docs:
<Switch>
的独特之处在于它专门呈现路由。相比之下,与位置匹配的每个 <Route>
都包含渲染。
这里发生的事情是您有 MainLayout
中断了您的 Switch
和您的 Route
组件之间的父/子关系。因此,Route
会采用其默认行为,即呈现所有与路径匹配的 Route
而不是第一个。
您需要在 Switch
内部引入一个额外的 MainLayout
组件,以便 Routes
有一个 Switch
作为它们的父级。此外,您应该将 Fragment
分支内的 isAuthenticated
替换为 Switch
。
const Root = () =>
<BrowserRouter>
<Switch>
<ProtectedRoute exact path="/:username/contact-networks" component={ContactNetworks} />
<ProtectedRoute exact path="/:username/tags" component={UserTags} />
<ProtectedRoute exact path="/:username/profile-picture" component={UserProfilePicture} />
<MainLayout nofooter={['/login']}>
<Switch>
<Route exact path="/" component={Home} />
{!isAuthenticated ? (
<Switch>
<Route exact path="/logup" component={Logup} />
<Route exact path="/login" component={Login} />
</Switch>) : <Redirect to="/" />}
<Route exact path="/users/:username" component={UserProfile} />
<Route exact path="/:username/catalog/:product" component={ProductPage} />
<ProtectedRoute exact path="/:username/products/new" component={PostProduct} />
<Route exact path="/:username/opinions" component={ClientsOpinions} />
<ProtectedRoute exact path="/:username/opinions/new" component={NewOpinion} />
<Route exact path="/:shop/contact" component={ShopContact} />
<Route exact path="/search/results" component={SearchResults} />
<Route component={NotFound} />
</Switch>
</MainLayout>
</Switch>
</BrowserRouter >