我已经阅读了Redux文档并发现如果我们能够设计初始对象,我们只能为整个应用程序编写一个reducer。
如果我是真的,这个实现是否有效,我只采用了一个减速器并根据我的要求设计了我的对象。
这是我的代码
import merge from 'lodash/object/merge';
const initialState = {
user: {isLoggedIn: false, showSignIn: false, showSignUp: false},
exams: {},
subjects: {isfetched: false},
units: {},
classRooms: [],
pricePlansSelected: {},
plansActiveState: { tabActive: 'popular' },
trackCPCClick: {},
pricingPlans: {},
popularPlans: {isfetched: false},
customPlans: {isfetched: false},
unitsForCustomSelection: {},
appliedCoupon: { code: '', applied: false},
examAttempts: {isfetched: false},
examAttemptSelected: {}
};
export default function entities(state = initialState, action) {
return merge({}, state, action);
}
答案 0 :(得分:0)
虽然技术上确实Redux商店使用一个减速器,但是将减速器分解为可读和可维护的部分是fundamental以便进行良好的Redux开发。最好的方法是为每个状态创建一个新的reducer函数,然后使用combineReducers()将所有这些部分组合回一个reducer函数。
使用你的几个州,你可以很好地将它分开:
import { combineReducers } from 'redux'
const userState = {isLoggedIn: false, showSignIn: false, showSignUp: false};
function userReducer(state = userState, action) {
//build new piece of state based on action here
}
const subjectState = {isfetched: false};
function subjectReducer(state = subjectState, action) {
//build new piece of state based on action here
}
const appState = combineReducers({
user: userReducer,
subject: subjectReducer
});
export default appState;
您发布的代码的主要问题是您需要在reducer函数中考虑所有可能的操作类型。否则,您的整个应用程序只能执行一次操作,每次都会使用其数据重建整个应用程序状态。您可以按照自己喜欢的方式考虑不同的操作类型,但主要约定是使用switch
。另请注意,当您使用lodash merge
创建状态时,如果您正在编译,还可以使用Object.assign()或spread operator(...三个点)执行相同的操作像巴贝尔这样的东西。
因此,考虑到这一点,你的一个reducer函数看起来像这样:
function userReducer(state = userState, action) {
switch (action.type) {
case 'LOAD_USER':
return action.result; //assumes action.result is same structure as user piece of state
case 'LOG_IN':
return {...state, isLoggedIn: true}
default:
return state;
}
}
由于您的reducer被分解为可维护的部分,因此您的操作只需返回与该特定状态相对应的数据,而不是整个应用程序。