首页 > 解决方案 > 用单独的页面反应包罗万象

问题描述

我看到了很多关于如何在 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 会在任何来自path='/'. 如果切换到exact path='/',则无法localhost:3000/users从用户登录时需要的 URL 访问。

Main

<Switch>
  <div className="someclass">  
    <Header />
    <Route exact path='users' component={Users} />
    <Footer />
  </div>
  <Route component={NotFound} /> . ** This also doesn't work here **
</Switch>

标签: reactjsreact-router

解决方案


看看下面的代码来达到你想要的结果:

               <Switch>                  
                {this.props.notLoggedIn === true
                  ? <Route path='/' component={LandingPage}/>                                          
                  : <Dashboard />                    
                }
                <Route component={PageNotFound}/>
              </Switch>    

在上述情况下,我将登录页面显示为默认路由,如果用户登录仪表板,则会显示(包含更多路由)。为了掌握用户是否经过身份验证,我auth通过登录页面中的提交来设置状态,例如

handleSubmit = (e) => {
    e.preventDefault()

    const { value} = this.state  
    const { dispatch } = this.props

    dispatch(setAuthedUser(value))
  }

在我的应用程序中之后,我可以访问它并设置notLoggedIn道具。看

function mapStateToProps ({ authedUser }) {
  return {
    notLoggedIn: authedUser === null
  }
}

如果没有匹配的路由,PageNotFound则显示组件。

有关完整代码,请查看 repo: Repo


推荐阅读