如何在react js中正确设置react路由器dom的身份验证流?

mspsb9vt  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(240)

我目前正在学习react js和react路由器dom。现在我想实现的是。如果令牌存在,如何自动将浏览器重定向到专用路由?因为现在即使我有令牌,redux loggedin status的状态为true,我仍然可以访问登录,这意味着我的privateroute组件工作不正常,你能帮我正确设置吗谢谢。
目标:如果用户已登录且令牌存在,则用户将不允许返回登录路由器。如果用户试图访问登录名,用户将返回privateroute组件。
受保护路线:

import React,{useEffect} from 'react'
import { Redirect, Route, useHistory, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { selectUser, login, logout } from '../features/userSlice';

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

    let {loggedIn} = useSelector((state) => state.user.login);

    const location = useLocation();

    useEffect(() => {
        !loggedIn && localStorage.getItem('token')
    },[loggedIn])

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

export default ProtectedRoute

app.js

const App = () => {

  let user = useSelector(selectUser); 

  return (
    <div className="App" >

        <Router>

          <Switch>

            <Route path="/login" exact component={Login}/>
            <Route path="/" exact component={Login}/>

            <MainLayout userProfile={user}>

              <ProtectedRoute path="/dashboard" exact component={Dashboard} />

              <ProtectedRoute path="/customer_payor" exact component={CustomerPayor} />

              <ProtectedRoute path="/bank" exact component={Bank} />

              <ProtectedRoute path="/check_in_remarks" exact component={CheckInRemarks} />

              <ProtectedRoute path="/bank_account" exact component={BankAccount} />

              <ProtectedRoute path="/user_list" exact component={UserList} />

              <ProtectedRoute path="/access_right" exact component={AccessRight} />

              <ProtectedRoute path="/receive_check" exact component={ReceiveCheck} />

              <ProtectedRoute path="/move_check" exact component={MoveCheck} />

              <ProtectedRoute path="/deposit_check" exact component={DepositCheck} />

              <ProtectedRoute path="/exchange_check" exact component={ExchangeCheck} />

            </MainLayout>

            <Route path="*" component={NotFound} />

          </Switch>

        </Router>

    </div>
  );
}

export default App;

redux州:

loggedIn(pin):true

本地存储:

如您所见,我制作了一个屏幕截图,我可以访问/和/登录的路径,即使我的loggedin=true,并且令牌存在。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题