React Catch-All 使用单独的页面

IT技术 reactjs react-router
2021-04-30 21:35:45

我看到了很多关于如何在 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='/',则无法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>
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))
  }

在我的应用程序中,我可以访问它并设置notLoggedInprops。

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

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

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