React.js中受保护的路由

时间:2020-04-09 14:26:40

标签: javascript reactjs

当我的应用程序初始化并在端口3000上启动时,我在Reactjs中面临受保护的路由的问题。第一次,它不重定向到登录组件。另外,我编写的逻辑是,没有身份验证,首先进入登录组件,然后如果手动输入路径“ / user / login”,则会显示登录组件。

我的布局组件

import React from 'react';
import { connect } from 'react-redux';
import Loadable from 'react-loadable';
import { BreadcrumbsItem } from 'react-breadcrumbs-dynamic';
import { Switch, Route, withRouter } from 'react-router-dom';

import { MAINTENANCE_MODE } from '../../common/constants';

import classes from './Layout.view.scss';
import ProtectedComponent from '../../components/ProtectedComponent';

const Loading = () => 'Loading...';

const Auth = Loadable({
  loader: () => import('../auth/Auth.container'),
  loading: Loading,
});

const Maintenance = Loadable({
  loader: () => import('../../components/Maintenance/Maintenance'),
  loading: Loading,
});

const Dashboard = Loadable({
  loader: () => import('../dashboard/views/dashboard'),
  loading: Loading,
});

const Layout = () => {
  return (
    <>
      <BreadcrumbsItem to="/" key="layout-breadcrumb">
        Home
      </BreadcrumbsItem>
      <div className={classes.layout}>
        <div className={classes.main}>
          <div className={classes.pageContent}>
            {MAINTENANCE_MODE === 'Yes'
              ? <Route path="/" component={Maintenance} />
              : (
                <Switch>
                  <Route
                    exact
                    path="/user/login"
                    component={Auth}
                  />
                  <ProtectedComponent
                    path="/dashboard"
                    component={Dashboard}
                  />
                </Switch>
              )}
          </div>
        </div>
      </div>
    </>
  );
};

Layout.defaultProps = {};

Layout.propTypes = {};

const mapStateToProps = () => ({});

export default withRouter(connect(mapStateToProps)(memo(Layout)));

我的保护路线组件

import React from 'react';
import { get } from 'lodash';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';

import storage from '../common/storage';

const ProtectedComponent = ({ component: Component, isAuthenticated }) => (
  <Route
    render={() => (
      (isAuthenticated || get(storage.get('user'), 'token'))
        ? <Component />
        : <Redirect to="/user/login" />
    )}
  />
);

ProtectedComponent.defaultProps = {
  isAuthenticated: false,
};

ProtectedComponent.propTypes = {
  component: PropTypes.any.isRequired,
  isAuthenticated: PropTypes.bool,
};

export default ProtectedComponent;

2 个答案:

答案 0 :(得分:2)

错别字:您将属性定义为Component,但在属性中以component传递。

<ProtectedComponent
   path="/dashboard"
   component={Dashboard}
  />

ProtectedComponent.propTypes = {
  Component: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.array,
  ]).isRequired,
  isAuthenticated: PropTypes.bool,
};

答案 1 :(得分:1)

import React, { Component } from 'react';
import auth from '../services/authService' // here i am checking local storage user is login 
import {
  Route,
  Redirect,
} from "react-router-dom";
class ProtectedRoute extends Component {
  render() { 
    const {path, component: Component, render, ...rest} = this.props
    return (  

      <Route
        path={path} 
        {...rest}
        render={ props => {
          if(!auth.getCuurentUser()) return <Redirect to={{
              pathname: '/login',
              state: {from: props.location}
          }}/>
          return  Component ? <Component {...props}/> : render(props);
        }}
        
        />
    );
  }
}
 
export default ProtectedRoute;

App.js 我在那里写我的路线

 <ProtectedRoute path="/contact" component={Contact} />