reactjs 如何将一个Redux减压器拆分为多个较小的减压器

eqoofvh9  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(91)

我是React & Redux的新手,正在开发我的应用程序的身份验证部分。
我的后端API的工作方式是,一旦用户登录,响应包含:

  • 用于将来请求的JWT标记
  • 包含用户数据的对象

我想做的是发生以下情况:
1.将令牌存储在localstorage
1.将Redux中的变量isAuthenticated设置为truefalse用于注销)
1.将用户信息存储在另一个Redux变量user
我目前有以下操作

import { SIGN_IN, SIGN_OUT } from "./Types";

export const signIn = response => {
    return {
        type: SIGN_IN,
        payload: response
    };
}

export const signOut = () => {
    return {
        type: SIGN_OUT
    };
}

和以下减速器

import { SIGN_IN, SIGN_OUT } from './Types';

const INITIAL_STATE = {
    isAuthenticated: null,
    user: {}
};

const authReducer = (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case SIGN_IN:
            // This logic was removed thanks to comment from Sanish Joseph
            // localStorage.setItem("token", action.payload.token);

            return {...state, isAuthenticated: true, user: action.payload.user};
        case SIGN_OUT:
            // This logic was removed thanks to comment from Sanish Joseph
            // localStorage.removeItem("token");

            return {...state, isAuthenticated: false, user: {}};
        default:
            return state;
    };
};

export default authReducer;

组合还原器代码:

export default combineReducers({
    ...
    auth: authReducer
});

这段代码可以工作,但是userisAuthenticated都是auth的子级(换句话说,我必须同时获得它们,并通过auth.userauth.isAuthenticated引用它们。
我不知道如何写我的reducer代码,这样SIGN_IN仍然会发送我从API获得的所有数据,但能够在Redux isAuthenticateduser中创建 *2个单独的 * 状态。
任何帮助都将不胜感激!

ibps3vxo

ibps3vxo1#

因此,我从这个问题中了解到,您希望将isAuthenticated和user作为存储中的两个独立部分。
为了将状态分成多个部分,您需要多个reducer。另一个需要记住的重要逻辑是,当任何操作被调度时,所有的reducer都将被调用。是否处理某个特定的操作由您决定。多个reducer可以处理同一个操作。
因此,要创建两个部件,一个用于auth,另一个用于user,您可以创建两个reducer。从auth reducer中删除用户处理,并将其添加到user reducer中。操作将是相同的。因此,在auth reducer中,

import { SIGN_IN, SIGN_OUT } from './Types';

const INITIAL_STATE = {
    isAuthenticated: null,
    
};

const authReducer = (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case SIGN_IN:           

            return {...state, isAuthenticated: true};
        case SIGN_OUT:          

            return {...state, isAuthenticated: false};
        default:
            return state;
    };
};

export default authReducer;

您的user reducer看起来会像这样:

import { SIGN_IN, SIGN_OUT } from './Types';

const INITIAL_STATE = {    
    user: {}
};

const userReducer = (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case SIGN_IN:
            

            return {...state,  user: action.payload.user};
        case SIGN_OUT:
           

            return {...state, user: {}};
        default:
            return state;
    };
};

export default userReducer;

别忘了把它们组合起来

export default combineReducers({
    ...
    auth: authReducer,
    user:userReducer
});

相关问题