我看到很多解决方案如何在SPA中创建无页面找到的路线,但似乎找不到任何SPA也使用单独的页面(如登录) .
例如:
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/" component={Main} />
** a catch all route wouldn't work here **
</Switch>
</Router>
对于像 <Route component={NotFound} />
这样的东西,全能路线不会起作用,因为路径将从 path='/'
触发 . 如果我切换到 exact path='/'
,那么我无法从URL访问 localhost:3000/users
,这是我在用户登录时所需要的 .
Main
:
<Switch>
<div className="someclass">
<Header />
<Route exact path='users' component={Users} />
<Footer />
</div>
<Route component={NotFound} /> . ** This also doesn't work here **
</Switch>
1 回答
请查看下面的代码以获得所需的结果:
在上面的例子中,我将登录页面显示为默认路由,如果用户登录,则显示仪表板(包含更多路径) . 为了处理用户是否经过身份验证,我通过登录页面中的提交设置
auth
状态在我的应用程序中,我可以访问它并设置
notLoggedIn
道具 . 看到如果没有匹配的路由,则显示
PageNotFound
组件 .有关完整代码,请查看回购:Repo