检查用户是否在 PrivateRoute 组件 React 上登录

我正在使用我的 Rails Api(DoorKeeper/Devise)上的用户身份验证制作我的第一个反应应用程序。我设置了expires_at反应local_storage并尝试在私有路由组件中进行验证。在这种情况下,我想验证用户令牌以让他访问路由“/”。我无法联系到 userSignedIn。如何从 PrivateRoute 组件访问此功能?


// PrivateRoute.js

import React from 'react';

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

import userSignedIn from '../auth'


const PrivateRoute = ({ component: Component, ...rest }) => (

  <Route {...rest} render={(props) => (

    userSignedIn === true

      ? <Component {...props} />

      : <Redirect to={{

          pathname: '/login',

          state: { from: props.location }

        }} />

  )} />

)


export default PrivateRoute;

// auth.js

const userSignedIn = () => {

  if (localStorage.getItem('expires_at') !== null) {

    return new Date() < new Date(localStorage.getItem('expires_at'))

  } else {

    return false

  }

}


export default userSignedIn;

谢谢


开心每一天1111
浏览 156回答 1
1回答

慕姐4208626

还没有时间测试这个,但是const PrivateRoute = ({ component: Component, ...rest }) => (&nbsp; <Route {...rest} render={(props) => (&nbsp; &nbsp; userSignedIn() === true&nbsp; &nbsp; &nbsp; ? <Component {...props} />&nbsp; &nbsp; &nbsp; : <Redirect to={{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pathname: '/login',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; state: { from: props.location }&nbsp; &nbsp; &nbsp; &nbsp; }} />&nbsp; )} />)您需要调用该函数,userSignedIn()因为它是返回值的内容true/false(这是此处唯一的更改)userSignedIn === true->userSignedIn() === true
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript