Javascript 在Redux中构建存储
有没有一种方法可以构造Javascript 在Redux中构建存储,javascript,reactjs,ecmascript-6,redux,react-redux,Javascript,Reactjs,Ecmascript 6,Redux,React Redux,有没有一种方法可以构造constreducer=(state=initialState,action),使方法不会因为一堆开关情况而膨胀 我的想法是将相关操作放入数组中,并在处理操作时使用Array.prototype.includes()检查它们 然后,我将提取与新方法中的特定操作相关的切换案例(例如,List组件将具有List\u ADD,List\u REMOVE等),并调用这些方法,而不是仅在const reducer=(state=initialState,action)方法中运行10
constreducer=(state=initialState,action)
,使方法不会因为一堆开关情况而膨胀
我的想法是将相关操作放入数组中,并在处理操作时使用Array.prototype.includes()
检查它们
然后,我将提取与新方法中的特定操作相关的切换案例(例如,List
组件将具有List\u ADD
,List\u REMOVE
等),并调用这些方法,而不是仅在const reducer=(state=initialState,action)
方法中运行100个案例
这将影响绩效,但至少是结构化的
有更好的主意吗?我使用了一个名为reduxsauce的库,它消除了对大型switch语句的需要 相反,它使用以下语法将操作绑定到方法:
export const INITIAL_STATE = {
values: {},
}
export const reducerFunction = (state, action) => {
const values = action.value;
return {
...state,
values,
};
};
// map the action types to the reducer functions
export const HANDLERS = {
[Type.ACTION_NAME]: reducerFunction,
...
}
// call createReducer to magically tie it all together
export default createReducer(INITIAL_STATE, HANDLERS);
官方Redux提供了非常方便的Redux创建者:
function createReducer(initialState, handlers) {
return function reducer(state = initialState, action) {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action)
} else {
return state
}
}
}
这使您可以按如下方式创建减速器:
const reducer = createReducer(initialState, {
[actionType.ACTION1]: specificActionReducer1,
[actionType.ACTION2]: specificActionReducer2,
}
没有开关语句 你也可以试试这个。允许您按如下方式组合减速器:
moduleA.reduce(SOME_ACTION, action => ({ state1: action.payload }))
moduleA.reduce(SOME_OTHER_ACTION, { state2: "constant" })
它还有一个额外的好处,即可以在任何地方访问reducer状态,例如在mapDispatchToProps中:
const mapDispatchToProps = dispatch => {
return {
onClick: () => {
dispatch(someAction(getState(moduleA.state1)));
}
};
};
酷,我会调查的。谢谢