简体   繁体   English

我想根据用户的角色在登录后重定向用户并阻止他们访问 React.js 中的此页面

[英]i want to redirect user after login based on their role and stop them to access this page in React.js

I had did this using Redux library and MongoDB and its works fine with this but now i am doing same thing with mysql so its not working well.我已经使用 Redux 库和 MongoDB 完成了此操作,并且它可以正常工作,但现在我正在使用 mysql 做同样的事情,所以它不能正常工作。 This logic always redirect all users to admin dashboard.此逻辑始终将所有用户重定向到管理仪表板。 i want do like, if i do isAdmin="true" it will redirect to admin dashboard and stop to going coordinator dashboard.我想这样做,如果我这样做 isAdmin="true" 它将重定向到管理仪表板并停止去协调员仪表板。 and if isCoordinator="true" then redirect to coordinator dashboard and not able to access admin dashboard.如果 isCoordinator="true" 则重定向到协调器仪表板并且无法访问管理仪表板。 how can i that?我怎么能这样

*This is my Admin.js file. *这是我的 Admin.js 文件。 where i did logic to private access path.我在哪里对私人访问路径进行逻辑处理。

import { useSelector } from "react-redux";
import { Route, Routes, Link, useNavigate } from "react-router-dom";
import UsersList from "./UsersList";
import UsersEntry from "./UsersEntry";
import Projects from "./projects/Projects";
import "./Admin.css"

export default function Admin() {
    let navigate = useNavigate();
const userState = useSelector(state=> state.loginUserReducer)
const {currentUser} =userState;
 useEffect(() => {
  // This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
    if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
       navigate('/coordinators');
       if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
        navigate('/');
     }
    }   
 }, []) 

*This is UserAction.js fie. *这是 UserAction.js fie。


export const loginUser = (user) => async (dispatch) => {
    dispatch({type: "USER_LOGIN_REQUEST"});
    try {
        const response = await axios.post("http://localhost:4000/login",user);
        console.log(response.data);
        dispatch({type:"USER_LOGIN_SUCCESS", payload: response.data});
        localStorage.setItem('currentUser',JSON.stringify(response.data));           
        window.location.href = "/admin"; 
        
    } catch (error) {
        dispatch({type: "USER_LOGIN_FAIL", payload: error})
    }
    }

*This is UserReducer.js. *这是 UserReducer.js。

switch (action.type){
  case "USER_LOGIN_REQUEST":
      return{
          loading:true,
      };
  case "USER_LOGIN_SUCCESS":
      return{
          success: true,
          loading: false,
          currentusers: action.payload,
      };
  case "USER_LOGIN_FAIL":
      return{
          error: action.payload,
          loading:false,
      };
  default:
      return state; 
 }
};

*This is Store.js. *这是 Store.js。

import thunk from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import {loginUserReducer} from './UserReducer';

const currentUser = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null 

const rootReducer = combineReducers({loginUserReducer :  loginUserReducer});

const initialState = {
    loginUserReducer: {
        currentUser : currentUser
    }
} 
const middleware = [thunk]

const store = createStore(
    rootReducer,
    initialState,
    composeWithDevTools(applyMiddleware(...middleware))
    );

    export default store;

In your useEffect inside the dependency array pass the currentUser so whenever it is changed useEffect will be triggered.在依赖项数组中的 useEffect 中传递currentUser ,因此无论何时更改 useEffect 都会被触发。 In current scenario when the array is empty it just happens on the page load the very first time.在当前情况下,当数组为空时,它只会在第一次加载页面时发生。

Here is the possible thing to try:这是可能尝试的事情:

 useEffect(() => {
  // This code check Role of user who logged in and if not coordinator then restrict(stop) to going on this private page. By getItem and check === !currentUser.isCoordinator.
    if(localStorage.getItem('currentUser') === null || !currentUser.isAdmin){
       navigate('/coordinators');
       if(localStorage.getItem('currentUser') === null || !currentUser.isCoordinator){
        navigate('/');
     }
    }   
 }, [currentUser]) <================

Secondly also check your nested if condition.其次还要检查你的嵌套 if 条件。 You can use an else if as well so incase its not admin it will go inside if and if it is admin then it can go inside the else if block .您也可以使用 else if 以防万一它不是 admin 它将 go inside if 如果它是 admin 那么它可以 go inside else if block But that is totally up to you, just a suggestion.但这完全取决于你,只是一个建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM