Phi*_*lts 8 reactjs redux react-redux
所以我正在开发一个大型的react/redux应用程序,并且非常满意它在redux中管理状态的简单程度.我们正在使用"ducks"风格的方法来减少/动作/动作创建者以保持相对基于域的东西.此外,我们尝试保持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;
}
}
Run Code Online (Sandbox Code Playgroud)
我们最终会为ui反复重复相同的操作,主要是切换和设置显示的内容.有没有办法将基于域的ui保留在reducer中,而无需在每个reducer中为ui 添加OPEN
和CLOSE
类型语句.也许我正在考虑的是redux中的反模式,但很想知道之前是否有人遇到过这类问题?
更新:
我喜欢下面列出的解决方案,但是如何将reducer扩展为包含ui reducer的类型.
combineReducers({
home: {createUiReducer('home', initialState), ...home}
})
Run Code Online (Sandbox Code Playgroud)
这样,您可以使用基于嵌套域的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"}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3366 次 |
最近记录: |