React JS Switch Router只有管理员页面没有访问我的404页面

时间:2017-09-12 05:15:58

标签: reactjs react-router

我想将我应用的部分内容限制为仅限登录用户。 我使用下面的代码工作。

但是,之前我正在使用 Switch 路由器在找不到匹配的路由时将用户发送到404页面。

由于某些原因,我将 EnsureLoggedIn 组件添加到 App.jsx 后,用户永远不会被重定向到404页面。

测试:在URL中输入随机路径。应该路由到404页面。

  • isLoggedIn = false :用户被定向到/ login页面。
  • isLoggedIn = true :找不到匹配的路由,并且页面容器呈现为空。

我希望交换机路由器忽略嵌套在 EnsureLoggedIn 中的内容,因为没有路由匹配,然后呈现404.

希望有更多React经验的人可以引导我。

App.jsx

<BrowserRouter>
  <Header/>
  <Switch>
   <Route exact path="/" component={HomePage}/>
   <Route exact path="/someotherpage" component={SomeOtherPage}/>
   <EnsureLoggedIn>
     <Route exact path="/dashboard" component={Dashboard}/>
   </EnsureLoggedIn>
   <Route component={Error404Page}/>
  </Switch>
  <Footer/>
</BrowserRouter>

EnsureLoggedIn.jsx

 class EnsureLoggedIn extends Component {

   constructor(props) {
     super(props);
     this.state = {isLoggedIn: false};
   }

   render() {
     const isLoggedIn = this.state.isLoggedIn;
     if (isLoggedIn) {
       return this.props.children
     } else {
        return ( <Redirect to="/login" /> );
     }
   }
 }

2 个答案:

答案 0 :(得分:1)

<Switch>呈现第一个匹配的子<Route> - 但无论如何都会呈现您的<EnsureLoggedIn>组件,并通过显式呈现其子项来绕过<Switch>排他性。我不确定是否支持这种层次结构。

考虑使用<LoggedInEnsuringDashboard>或类似内容并将其直接放入Router而不进行嵌套。

编辑:

有些事情:

<BrowserRouter>
  <Header/>
  <Switch>
   <Route exact path="/" component={HomePage}/>
   <Route exact path="/someotherpage" component={SomeOtherPage}/>
   <Route exact path="/dashboard" component={LoggedInEnsuringDashboard}/>
   <Route component={Error404Page}/>
  </Switch>
  <Footer/>
</BrowserRouter>

并且

class LoggedInEnsuringDashboard extends Component {

   constructor(props) {
     super(props);
   }

   render() {
     if (this.props.isLoggedIn) {
       return <Dashboard>
     } else {
        return <Redirect to="/login" />
     }
   }
 }

答案 1 :(得分:0)

提供另一种我最终使用的方法。

这涉及创建一个名为UserArea的容器,该容器将所有仅限管理员的页面列为子容器。

然后在渲染功能中,如果用户未登录,以下内容可确保任何以/ user-area开头的url将被重定向到登录页面。

this.isLoggedIn() ? (<UserArea />) : (<Redirect to="/login" />) )

<强> App.jsx

<BrowserRouter>
  <Header/>
  <Switch>
   <Route exact path="/" component={HomePage}/>
   <Route exact path="/someotherpage" component={SomeOtherPage}/>
   <Route exact path="/login" component={LoginPage}/>
   <Route path="/user-area" render={ ()=>(this.isLoggedIn() ? (<UserArea />) : (<Redirect to="/login" />) )} />
   <Route component={Error404Page}/>
  </Switch>
  <Footer/>
</BrowserRouter>

<强> UserArea.jsx

<BrowserRouter>
  <main className="ks-main-content ks-container__user-area">
    <UserAreaHeader />
      <Switch>
      <Route exact path="/user-area/dashboard" component={UserAreaDashboardPage}/>
      <Route exact path="/user-area/profile" component={UserAreaProfile}/>
      <Route component={Error404Page} />
    </Switch>
  </main>
</BrowserRouter>