如何将一个 Redux reducer 拆分成多个较小的 reducer

How to split one Redux reducer into multiple smaller ones

我是 React 和 Redux 的新手,正在研究我的应用程序的身份验证部分。

我的后端 API 的工作方式是,一旦用户登录,响应包含:

我想做的是发生以下情况:

  1. 将令牌存储在localstorage
  2. 将 Redux 中的变量 isAuthenticated 设置为 truefalse 用于注销)
  3. 将用户信息存储在名为 user
  4. 的第二个 Redux 变量中

我目前有以下操作

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

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

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

和以下 Reducer:

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;

CombineReducers代码:

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

此代码有效,但 userisAuthenticated 都是 auth 的子代(换句话说,我必须同时获取它们并通过 [=21= 引用它们] & auth.isAuthenticated.

我不知道如何编写我的 reducer 代码,这样 SIGN_IN 仍然会发送我从 API 获得的所有数据,但能够创建 Redux isAuthenticated & user.

中 2 个独立的状态

非常感谢任何帮助!

所以我从问题中了解到,您想将 isAuthenticated 和 user 作为商店中的 2 个独立部分。

为了将状态分成多个部分,您将需要多个减速器。另一个需要记住的重要逻辑是,当任何 action 被调度时,你所有的 reducer 都会被调用。是否处理特定操作由您决定。多个减速器可以处理相同的动作。

因此,要创建 2 个部分,一个用于 auth,一个用于 user,您可以创建 2 个减速器。从 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
});