简体   繁体   中英

Proper way to delete particular property from main state of Redux which uses combineReducers - React Redux

I have an app where I want to implement authorization (registration, login, logout). I must use redux for that. So far registration and login is working great, but I'm getting problems when I should delete data of the logged user when the user clicks the logout button.

I tried to put the login and logout cases in the same reducer, but when a user was logged I can't get access to the user's data, and instead of just take the old users data object and return the empty one it just adds an empty object to the user's data.

My redux state before login:

在此处输入图像描述

My redux state after login:

在此处输入图像描述

My redux state after logout

在此处输入图像描述

Here is my actions for login and logout:

export function userLoginSuccess(user) {
    return {
        type: 'USER_LOGIN_SUCCESS',
        user
    }
}

export function userLogout() {
    return {
        type: 'USER_LOGOUT'
    }
}

Here is the reducer:

export function userLogin(state = {}, action) {
    switch (action.type) {
        case 'USER_LOGIN_SUCCESS':
            localStorage.setItem('userToken', action.user.token);
            return action.user;
        case 'USER_LOGOUT':
            localStorage.removeItem('userToken');
            return {
                ...state,
                userLogin: {}
            }
        default:
            return state;
    }
}

Here is the store initialization with combineReducers :

import { userLogin, companies, dataHaveError, dataIsLoading } from './redux/reducers';

const rootReducer = combineReducers({
  companies,
  userLogin,
  dataHaveError,
  dataIsLoading
})

const enhancer = applyMiddleware(thunk);

const store = createStore(rootReducer, {}, composeWithDevTools(enhancer));

I was trying to find a solution, but all that I find was without combineReducers and they were using initialState for solving this kind of problems, but in this case, how I understood, combineReducers is creating a state property for each reducer so I don't know how to handle this particular problem.

export function userLogin(state = {}, action) {
    switch (action.type) {
        case 'USER_LOGIN_SUCCESS':
            localStorage.setItem('userToken', action.user.token);
            return action.user;
        case 'USER_LOGOUT':
            localStorage.removeItem('userToken');
            return {} // return empty state
        default:
            return state;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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