如果用户未通过身份验证,如何在登录页面上输入任何URL时显示404页面?

时间:2019-05-30 08:50:52

标签: reactjs react-router

例如,如果用户未通过身份验证,我希望通过从登录屏幕访问无效URL来阻止用户,例如,考虑用户在登录屏幕上,并且如果用户尝试访问任何随机URL localhost:3000/kanskd,则他/她应该重定向到登录屏幕。我可以通过放置NoMatch路由组件来实现所需的功能,但是,它也与我的应用程序内部的路由匹配,并且也没有为这些路由提供匹配项。[我在NoMatch路由之后映射的路由没有工作]。

  

index.js

import Routes from './routes'

   <Switch>
       <Route exact path="/" render={() => {
          if(!store.getState().login.isAvailable) {
            return <Redirect to="/login"/>
          } else {
            return <Redirect to="/dashboard" />
          }             
        }} 
       /> 
       <Route exact path="/login" component={Login} />
       <Route component={NoMatch} />
       {Routes.map((prop, key) => {
          return <Route path={prop.path} key={key} component={prop.component} 
                  />;
       })}

   </Switch>
  

NoMatch.jsx

import React from 'react'
import { withRouter } from 'react-router-dom';

const NoMatch = ({ location }) => (
    <div>
      <h3>No match for <code>{location.pathname}</code></h3>
    </div>
)

export default withRouter(NoMatch);

编辑:

  

routes / index.js

import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/", name: "Dashboard", component: Dashboard }];

export default Routes;

用户登录后,会将其路由到仪表板,并且在仪表板中,还有其他多条路由。

1 个答案:

答案 0 :(得分:0)

因此,您必须在此处解决两件事:在网址不匹配时显示NoMatch组件,并保护一些未登录用户的路由。

对于第一个,您应该将<Route component={NoMatch} />放在<Switch>结束标记之前,将其视为普通javascript中的开关,最后一种情况始终是default情况,如果没有其他匹配项,则将执行default,与此处相同。

第二个问题需要一些额外的代码,如果未登录,您必须创建一个用于重定向用户的组件,如下所示(来自文档react-router文档):

function PrivateRoute({ component: Component, isLoggedIn,...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}

然后将此组件用于受保护的路由:

<Switch>
    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Redirect to="/dashboard" />
       }             
     }} 
    /> 
    <Route exact path="/login" component={Login} />
    {Routes.map((prop, key) => {
       return <PrivateRoute path={prop.path} key={key} component={prop.component} isLoggedIn={isUserLoggedIn} 
               />;
    })}
    <Route component={NoMatch} />
</Switch>

isUserLoggedIn是一个虚构变量,您应在登录检查方法后替换它

编辑: 路径应为/dashboard

import Dashboard from "Dashboard/Dashboard.jsx";

var Routes = [{ path: "/dashboard", name: "Dashboard", component: Dashboard }];

export default Routes;

如果您希望将/保留为路径,则应将Route组件内的仪表板组件返回,而不是重定向:

    <Route exact path="/" render={() => {
       if(!store.getState().login.isAvailable) {
         return <Redirect to="/login"/>
       } else {
         return <Dashboard/>
       }             
     }} 
    /> 
相关问题