【问题标题】:React Catch-All with Separate Pages用单独的页面反应包罗万象
【发布时间】:2018-12-10 03:38:34
【问题描述】:

我看到了很多关于如何在 SPA 中创建找不到页面的路由的解决方案,但似乎无法为也使用单独页面(如登录)的 SPA 找到任何东西。

例如:

<Router>
  <Switch>
    <Route path="/login" component={Login} />
    <Route path="/" component={Main} />
    ** a catch all route wouldn't work here **
  </Switch>
</Router>

catch-all 路径不适用于&lt;Route component={NotFound} /&gt; 之类的东西,因为路径会在来自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>

【问题讨论】:

标签: reactjs react-router


【解决方案1】:

看看下面的代码来实现你想要的结果:

               <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

【讨论】:

  • 感谢您的回复——这是我没有想到的角度。我的方法类似于{notLoggedIn === true ? ( &lt;Route path="/" component={Login} /&gt; ) : ( &lt;Main /&gt; )}。但是,最好重定向到/login,而不是在 URL/ 中显示登录组件。另一个限制是,如果我输入一个不存在的用于 Main 的 URL,它不会捕获它,除非我在 Main 中指定一个路由捕获 - 但是 NotFound 组件将与其他组件一起显示,例如我通常不会的侧边栏想要。
  • 我会支持你的答案,如果我有足够的声誉,如果没有其他问题,我也会标记为解决方案。谢谢。
  • 很高兴知道它对您有所帮助。要接受答案,您不需要声望。也接受答案获得 + 2 代表 (stackoverflow.com/help/accepted-answer)
  • 另外if I enter a URL intended for Main that does not exist, it will not catch it unless I specify a route catch in Main 您不必这样做。 Switch 的行为不是那样的.. Page not found 将显示 1) 如果用户未登录 2) 没有路由匹配,包括 Main
猜你喜欢
  • 1970-01-01
  • 2018-08-02
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 2011-02-12
  • 2011-09-09
  • 1970-01-01
相关资源
最近更新 更多