我有一个反应路由器开关,但 404 页面不起作用
<Switch>
<Route path="/login" component={Login} />
<Layout>
<ProtectedRoute exact path="/home" component={Home} />
<ProtectedRoute exact path="/profiles" component={Profiles} />
<ProtectedRoute exact path="/profiles/alarms" component={Alarms} />
<ProtectedRoute exact path="/profiles/:id" component={Profile} />
</Layout>
<ProtectedRoute component={NotFound} />
</Switch>
每当我将 url 更改为诸如“/tewyu”之类的随机网址时。该页面仅显示空白,不会转到 404 页面。感觉就像其中一条路线正在赶上
答案 0 :(得分:1)
听起来您有两个基本视图,一个带有导航栏和特定布局的应用,以及一个身份验证页面。
您可以将嵌套的 Layout
组件包装在一个通用路由中,并将嵌套的路由渲染到另一个 Switch
中进行匹配。
<Switch>
<Route path="/login" component={Login} />
<Route>
<Layout> // <-- navbar and layout
<Switch>
<ProtectedRoute exact path="/home" component={Home} />
<ProtectedRoute exact path="/profiles" component={Profiles} />
<ProtectedRoute exact path="/profiles/alarms" component={Alarms} />
<ProtectedRoute exact path="/profiles/:id" component={Profile} />
<ProtectedRoute component={NotFound} />
</Switch>
</Layout>
</Route>
</Switch>
当然,您也可以将通用 Route
组件设为 ProtectedRoute
,然后在此身份验证“检查点”内呈现普通 Route
组件。