【问题标题】:What is the best way to make private route in reactjs在 reactjs 中创建私有路由的最佳方法是什么
【发布时间】:2020-10-09 05:29:57
【问题描述】:

我在我的应用程序中创建了一条私有路由,基本上我的应用程序中的所有路由都是私有的。因此,为了制作私有路由,我添加了一个状态isAuthenticated,默认情况下为 false,但当用户登录时,它变为 true。所以在这个isAuthenticated 状态下,我在私有路由组件中实现了一个条件。但是这个问题是当用户登录并刷新页面时。我被重定向到/ 主页。我不想那样。

我在这里使用令牌认证。

这是我的 PrivateRoute.js

import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";

const PrivateRoute = ({ isAuthenticated, component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
    }
  />
);

function mapStateToProps(state) {
  return {
    isAuthenticated: state.user.isAuthenticated,
  };
}

export default connect(mapStateToProps)(PrivateRoute);

【问题讨论】:

  • 在用户登录后将token存储在localStorage中,并检查该localStorage中是否存在令牌。如果没有,请注销用户。如果是,让用户输入您的private route
  • 如果我同时使用经过身份验证和令牌可以吗?
  • 最好从 localStorage 令牌更新isAuthenticated。因为那将是真相的来源。应该有一个操作将isAuthenticated 设置为 true 在从 localStorage 获得令牌后,以便您应用程序中的所有组件都知道该用户已通过身份验证。

标签: javascript reactjs


【解决方案1】:

如果您在通过身份验证时的所有路由都是私有的,您也可以跳过按路由进行身份验证并使用以下方法

import PrivateApp from './PrivateApp'
import PublicApp from './PublicApp'


function App() {
   // set isAuthenticated dynamically
   const isAuthenticated = true

   return isAuthenticated ? <PrivateApp /> : <PublicApp />
}

这样,您无需考虑每条路由是否经过身份验证,只需定义一次,然后根据具体情况呈现您的私有或公共应用程序。在这些应用程序中,您可以正常使用路由器,而无需考虑谁可以访问哪个路由。

【讨论】:

    【解决方案2】:

    如果您针对服务器验证令牌(您应该这样做),那么这是一个异步操作,isAuthenticated 最初将是虚假的,从而导致刷新时重定向。

    解决此问题的一种方法是isAuthenticating 状态,例如

    import React from "react";
    import { connect } from "react-redux";
    import { Route, Redirect } from "react-router-dom";
    
    const PrivateRoute = ({ isAuthenticated, isAuthenticating, component: Component, ...rest }) => (
      <Route
        {...rest}
        render={(props) => {
          if( isAuthenticating ){ return <Spinner /> }
          return isAuthenticated ? <Component {...props} /> : <Redirect to="/" />
          }
        }
      />
    );
    
    function mapStateToProps(state) {
      return {
        isAuthenticated: state.user.isAuthenticated,
        isAuthenticating: state.authentication.inProgress
      };
    }
    
    export default connect(mapStateToProps)(PrivateRoute);
    

    isAuthenticating 应默认为true,然后在收到服务器响应且已知user.isAuthenticated 状态时设置为false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 2019-11-28
      • 2017-08-06
      • 1970-01-01
      • 2021-10-03
      • 2021-07-14
      • 2019-08-10
      相关资源
      最近更新 更多