ReactJS:如果用户未登录,则重定向到登录页面

时间:2021-04-15 15:38:14

标签: reactjs redirect redux token dispatch

我有点困惑,不知道为什么我的功能不起作用。 事实上,如果令牌不在 LocalStorage 中,我想将用户重定向到登录页面。 我使用 Redux,所以有一个 authReducer 和一个 userActions”。 我的应用程序不会重定向用户! 提前致谢

我的 authReducer...

import { authConstants } from "../../constants/userConstants"; 

export const authReducer = (state = { user: {}, token: null, roles:{}, isAuthenticated: false, 
isRegistered: true }, action) => {
switch (action.type) {

    case authConstants.REGISTER_USER_REQUEST:
        return {
            loading: true,
            isRegistered: false
        }
        
    case authConstants.LOGIN_REQUEST:
    case authConstants.LOAD_USER_REQUEST:
        return {
            loading: true,
            isAuthenticated: false,
        } 

    case authConstants.LOGIN_SUCCESS:
    case authConstants.LOAD_USER_SUCCESS:
        return {
            ...state,
            loading: false,
            isAuthenticated: true,
            user: action.payload.user.username,
            token: action.payload.token,
            roles: action.payload.roles
        }

    case authConstants.REGISTER_USER_SUCCESS:
        return {
            ...state,
            loading: false,
            isRegistered: true,
            
        }

    case authConstants.LOGOUT_SUCCESS:
        return {
            loading: false,
            isAuthenticated: false,
            user: null
        }

    case authConstants.LOAD_USER_FAIL:
        return {
            loading: false,
            isAuthenticated: false,
            user: null,
            error: action.payload
        }

    case authConstants.LOGOUT_FAIL:
        return {
            ...state,
            error: action.payload
        }

    case authConstants.LOGIN_FAIL:
    case authConstants.REGISTER_USER_FAIL:
        return {
            ...state,
            loading: false,
            isAuthenticated: false,
            user: null,
            message: action.payload
        }

    case CLEAR_ERRORS:
        return {
            ...state,
            error: null
        }

    default:
        return state
  }
 }

我的 authActions

import { authConstants } from "../../constants/userConstants"
import axios from "axios";
import { toast } from 'react-toastify';

export const login = (user) => {
console.log("test ", user);

return (dispatch) => {
    dispatch({
        type: authConstants.LOGIN_REQUEST
    });

    axios.post('/login', {
        ...user,
    })
    .then((response) => {
        if(response.data.success === true){
            const { token, user, roles } = response.data;
            // console.log(response.data.user.token)
            localStorage.setItem('token', user.token);
            localStorage.setItem('user', JSON.stringify(user.username));
            localStorage.setItem('roles', user.roles);
            toast.success("Successfully Connected !");
            dispatch({
                type: authConstants.LOGIN_SUCCESS,
                payload: { token, user, roles }
            });
        }else{
            if (response.data.success === false) {
                // console.log(response.data.full_messages[0])
                toast.error(response.data.full_messages[0]);

                dispatch({
                    type: authConstants.LOGIN_FAIL,
                    payload: { message: response.data.full_messages[0] }
                });
            } 
        }
    })
    .catch((error) => {
        console.log("Oops, Request failed!");
    });
    }
    }

我的根文件的一部分。这是我的登录页面和仪表板路线,我验证要重定向的令牌的逻辑

class Root extends Component {
render() {
    return (
        <Provider store={store}>
            <BrowserRouter basename={'/'}>
                <ScrollContext>
                    <Switch>
                        <Route path='/login' component={Login} />
                        {/* <Route exact path='/login' component={Login} /> */}
                        <App>
                            <Route exact path='/' component={Dashboard} />
                                         .
                                         .
                                         .
                                         
          if (token) {

               console.log(token);
               store.dispatch(login)

          }else{
             store.dispatch({ type: authConstants.LOGIN_FAIL });
          }
    ReactDOM.render(<Root />, document.getElementById('root'));

我非常感谢您的回答。谢谢!

1 个答案:

答案 0 :(得分:0)

您可以查看此答案:How to restrict access to routes in react-router?

基本上,您将创建一个包装组件来检查登录状态。