使用react-router-dom在reactJS中进行身份验证的路由

问题描述 投票:2回答:1

描述::

我正在研究reactJS应用程序并使用react-router-dom进行路由。如果用户没有进行身份验证,则会转到“http://localhost:3000/login”,成功登录后会重定向到“http://localhost:3000/dashboard”。重新加载此页面后,它会显示空白页面。

为了解决这个问题,我在我的基本网址之后添加了“/ app”,现在它出现在每个路由网址之前,现在内部网页路由就像“http://localhost:3000/app/dashboard”。但是我不想在每个路由元素之前添加“app”,我需要路由url应该是base_url / page路由路径。

空白页面路由::

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

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

class App extends Component {
   constructor(props) {
      super(props);
   }

   render() {
      let isUserLogggedIn = localStorage.getItem('isUserLoggedIn');
      const { location, match } = this.props;
      let url = location.pathname.split('/');
      if (location.pathname === '/login') {
         localStorage.clear();
      }
      if (location.pathname === '/') {
         if (!isUserLogggedIn) {
            return (<Redirect exact from='/' to={`${match.url}login`} />);
         } else {
            return (<Redirect exact from='/' to={`${match.url}app`} />);
         }
      }
      if ((url[1] !== "app") && (url[1] !== "login")) {
         return (<Redirect exact from={location.pathname} to={`${match.url}login`} />);
      }
      return (
         <>
            <BrowserRouter>
               <Switch>
                  <InitialPath
                     path={`${match.url}app`}
                     authUser={isUserLogggedIn}
                     component={DefaultLayout}
                     location={location}
                  />
                  <Route path='/login' component={Login} />
               </Switch>
            </BrowserRouter>
         </>
      );
   }
}

export default App;

如果从root用户删除“app”,则其工作继续并出现错误。

错误::

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
reactjs react-router-dom
1个回答
0
投票

我认为没有网址问题。

试图将localStorage的东西处理成render方法并不是最好的主意。你应该使用生命周期方法,即componentDidMountcomponentDidUpdate

您的App组件似乎被逻辑所淹没。 auth-logic应该进入Login组件,当它(Login)安装它应该清除存储。当用户成功进行身份验证时,它(Login)应将会话ID保存到存储中。

接下来的事情是自己搞乱位置是没有必要的,让react-router为你做这件事。

class App extends Component {
  componentDidUpdate () {
    this.setState({ isUserLoggedIn: !!localStorage.getItem("isUserLoggedIn") });
  }

  render () {
    const { isUserLogggedIn } = this.state;

    return (
      <BrowserRouter>
        <Switch>
          <InitialPath
            path="/dashboard"
            authUser={isUserLogggedIn}
            component={DefaultLayout}
            location={location}
          />
          <Route path="/login" component={Login} />
        </Switch>
      </BrowserRouter>
    );
  }
}

class Login extends Component {
  componentDidMount () {
    localStorage.removeItem("isUserLogggedIn");
  }

  render () {
    // some render stuff
    //
    // after successfull login
    // you should save `isUserLogggedIn` into localStorage 
    // and redirect to the main page
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.