所以我正在开发一个大型react/redux应用程序,并且对redux中管理状态的简单程度非常满意。我们对reducer/action/action creator使用了一种"鸭子"风格的方法,以保持事物相对基于领域。此外,我们试图保持ui状态与域相关联,大多数reducer都有类似的结构。它看起来像这样:
export default function home(state = initialState, action = {}) {
switch (action.type) {
case OPEN:
return {
...state,
ui: {
...state.ui,
[action.key]: true
}
};
case CLOSE:
return {
...state,
ui: {
...state.ui,
[action.key]: false
}
};
case SELECT_TAB:
return {
...state,
ui: {
selectedTab: action.selected
}
};
default:
return state;
}
}
我们最终在ui中重复了相同的操作,主要是切换和设置显示的内容。是否有一种方法来保持基于域的ui在一个减速器中,而不必在每个减速器的ui中添加OPEN
和CLOSE
类型语句。也许我想的是redux中的反模式,但我想知道是否有人以前遇到过这种问题?
更新:
我喜欢下面列出的解决方案,但是你如何扩展这个reducer来包含一个ui reducer呢?
combineReducers({
home: {createUiReducer('home', initialState), ...home}
})
这样你就可以拥有嵌套的基于域的ui,而不需要重复所有的操作。我不知道该怎么做因为你实际上是在动态地添加CASE语句
你需要用一个前缀命名它们。如果你像大多数开发人员一样懒惰,那么创建一个帮助函数来为你生成reducer;)
就像这个…
const createOpenCloseReducer = (prefix, initialState) => {
const = ui = prefix + "_UI";
return (state = initialState, action) => {
switch(action.type) {
case (prefix + "_CLOSE"):
return { ...state, [ui]: "CLOSED" }
case (prefix + "_OPEN"):
return { ...state, [ui]: "OPENED" }
default:
return state
}
}
}
import { combineReducers, createStore } from 'redux';
const rootReducer = combineReducers({
home: combineReducers({
ui: createOpenCloseReducer("HOME", { "HOME_UI": "CLOSED" }),
data: someOtherHomeDataReducer
}),
someOther: createOpenCloseReducer("OTHER", { "OTHER_UI": "CLOSED" })
})
store = createStore(rootReducer)
// use it..
store.dispatch({type: "HOME_CLOSE"})
store.dispatch({type: "OTHER_OPEN"})
// your state..
store.getState().home.ui // {HOME_UI: "CLOSED"}
store.getState().someOther // {OTHER_UI: "OPENED"}