登录后具有侧边栏视图的React-web-redux Auth

时间:2019-03-05 02:30:01

标签: javascript reactjs react-router-v4 redux-router

我有我的react-web-redux-router应用程序,具有正常的登录名和主页。 问题是登录名和主页重定向以及侧栏主链接重定向工作正常。请参见下面的图像。

登录页面: Login Page

首页: Home Page

导航栏重定向: Navbar Redirection

如上所示,图像重定向工作正常。

我的问题是导航栏有一些内部页面,重定向无法正常工作。

  1. 此外,当您刷新时,它会重定向到任何空白页Page on refresh

  2. 页面已加载,但没有重定向或页面呈现

页面加载: Page Loads

无重定向: No redirection

我将在下面上传一些示例代码,以便您了解我的侧边栏的工作方式和身份验证流程

App.js

<Router history={history}>
  <div>
    <PrivateRoute exact path="/" component={HomePage} />
    <Route path="/login" component={props => <LoginPage {...props {...this.props} />} />
 </div>
</Router>

PrivateRoute.js

<Route {...rest} render={props => (
    localStorage.getItem('user')
        ? <Component {...props} />
        : <Redirect to={{ pathname: '/login', state: { from: 
  props.location } }} />
)} />

HomePage.js

 const routes = [
          {
            path: "/",
            exact: true,
            sidebar: () => <Home/>,
            main: () => <Home/>
          },
          {
            path: "/link6",
            sidebar: () => <Link6/>,
            main: () => <Link6/>,
            routes: [
              {
                path: "/link6/bus",
                component: <div>Inner</div>
              },
              {
                path: "/link7/cart",
                component: <div>Inner again</div>
              }
            ]
          },
          {
            path: "/link7",
            sidebar: () => <Link7 />,
            main: () => <Link7 />
          }
        ];


        class HomePage extends React.Component {
          constructor(props){
            super(props)
            this.state = {
              active: '',
              navBarTitle: 'Dashboard',
            }
          }

          clicked(id, name){
            console.log(name)
           this.setState({
             active: id,
             navBarTitle: name
           })
          }
          render() {
            console.log(this.props)
            const { user } = this.props.authentication
            const { active, navBarTitle } = this.state
            return (
              <Router>
                <div className="d-flex" id="wrapper">
                  <SideMenu match={this.props.match} click={(id, name) => this.clicked(id,name)} active={active}/>
                  <div id="page-content-wrapper">
                    <div className="d-flex flex-column customNav">                             
                      <NavBar user={user}/>
                      <h1 className="mx-3 text-light" id="menu-toggle">{navBarTitle} </h1>
                    </div>
                    <div className="container-fluid">
                    {routes.map((route, index) => (
                    // You can render a <Route> in as many places
                    // as you want in your app. It will render along
                    // with any other <Route>s that also match the URL.
                    // So, a sidebar or breadcrumbs or anything else
                    // that requires you to render multiple things
                    // in multiple places at the same URL is nothing
                    // more than multiple <Route>s.
                      <Route
                        key={index}
                        path={route.path}
                        exact={route.exact}
                        component={route.sidebar}
                      />

                      ))}
                    </div>
                    <Footer />
                  </div>
              </div>        
              </Router>
            );
          }
        }

Sidebar.js

 const menuArray= [
      {
        id:1,
        name: "Link 1",
        icon: "handMoney",
        link: '/',
      },
      {
        id:2,
        name: "Link 2",
        icon: "product",
        link: '/',
      },
      {
        id:3,
        name: "Link 3",
        icon: "fileEdit",
        link: '/',
      },
      {
        id:4,
        name: "Link 4",
        icon: "fileSetting",
        link: '/',
      },
      {
        id:5,
        name: "Link 5",
        icon: "userSetting",
        link: '/',
      },
      {
        id:6,
        name: "Link 6",
        icon: "building",
        link: '/link6'
      },
      {
        id:7,
        title: "",
        name: "Link 7",
        icon: "multipleUser",
        link: '/link7'
      },
    ]
    export default class SideMenu extends React.Component{

      render() {
        return(
          <div className="noFlex shadow" id="sidebar-wrapper">
            <div className="p-3 my-4 mx-2">
              <img src={logo} className="img-fluid" alt="Xpress Cover" />
            </div>
            <span className="borderBottom mx-3"></span>
            <div className="list-group list-group-flush py-2">
              {
                menuArray.map(data => {
                  return(
                    <Link key={data.id} onClick={() => this.props.click(data.id,data.name)} to={data.link} className={"list-group-item navStyle list-group-item-action" + (this.props.active === data.id ? " activeNav" : ' text-info')}>
                      <i className={"icon-"+ data.icon}></i>&nbsp;  {data.name}
                    </Link>
                  )
                })
              }
            </div>
          </div>
        )
      }

Edit.js

  <Link to={'/link6/bus'}>
        <button className="buttonStyle mx-1" onClick={this.buttonClick}>
          <i  className={"icon-" +iconName+ " text-primary"}></i>      
        </button>   
      </Link>

2 个答案:

答案 0 :(得分:0)

尝试编辑PrivateRoute.js

if (localStorage.getItem('user')) {
  return <Route {...rest} render={props => <Component {...props} />} />
} else {
  return <Redirect to={{ pathname: '/login', state: { from: 
    props.location } }} />
}

可以吗?

答案 1 :(得分:0)

我在菜单中的导航链接:

 <NavLink to="/agenda">
   <Title>Agenda</Title>
 </NavLink>

路线

import React from 'react';

import styled from 'styled-components';

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { PrivateRoute, PublicRoute } from './utils/routeAuth';

import Dashboard from './pages/Dashboard';
import Login from './pages/Login';
import Menu from './components/Menu';

const Body = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
  background: #edeef0;
  overflow: auto;
`;

const Routes = () => (
  <BrowserRouter>
    <Switch>
      <PublicRoute path="/login" component={Login} />
      <PrivateRoute component={DefaultContainer} />
    </Switch>
  </BrowserRouter>
);

const NotFound = () => <div>not found</div>;

const DefaultContainer = () => (
  <Body>
    <Route component={Menu} />

    <Route path="/" exact component={Dashboard} />
    <Route path="/agenda" component={Dashboard} />
    <Route path="/alunos" component={Dashboard} />
    <Route path="/turmas" component={Dashboard} />
    <Route component={NotFound} />
  </Body>
);

export default Routes;

utils / routeAuth

import React from 'react';

import { Route, Redirect } from 'react-router-dom';

import { getCookie } from './cookie';

export const PrivateRoute = ({ component: Component, ...rest }) => {
  const isAuthenticated = getCookie('token');

  return (
    <Route
      {...rest}
      render={props => (isAuthenticated ? (
        <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        ))
      }
    />
  );
};

export const PublicRoute = ({ component: Component, ...rest }) => {
  const isAuthenticated = getCookie('token');

  if (isAuthenticated) {
    return <Redirect to="/" />;
  }

  return <Route {...rest} component={Component} />;
};

了解更多详细信息:Read more about the new Array.prototype.flat()auth page