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



我是React新手& &;Redux和我在我的应用程序的身份验证部分工作。

我的后端API的工作方式是,一旦用户登录,响应包含:
  • 用于未来请求的JWT令牌
  • 包含用户数据的对象

我想做的是让下面的事情发生:

  1. 将令牌存储在localstorage
  2. 在Redux中设置变量isAuthenticatedtrue(注销为false)
  3. 在第二个Redux变量user
  4. 中存储用户信息

我目前有以下动作:

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的孩子(换句话说,我必须获得它们并通过auth.user&auth.isAuthenticated.

我不知道如何做的是如何编写我的减速机代码,所以SIGN_IN仍然会发送我从API得到的所有数据,但能够创建2个独立的状态在ReduxisAuthenticated&user.

任何帮助都将非常感激!

所以我从这个问题中理解的是,你想让isAuthenticated和user作为商店中的两个独立部分。

为了将状态分成多个部分,您将需要多个减速机。另一个需要记住的重要逻辑是,当任何操作被分派时,所有的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;

和你的用户减速器看起来像,

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
});

最新更新