所以我正在研究一个大型的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,[action.key]: false } }; case SELECT_TAB: return { ...state,ui: { selectedTab: action.selected } }; default: return state; } }
我们最终会为ui反复重复相同的操作,主要是切换和设置显示的内容.有没有办法将基于域的ui保留在reducer中,而无需在每个reducer中为ui添加OPEN和CLOSE类型语句.也许我正在考虑的是redux中的反模式,但很想知道以前是否有人遇到过这类问题?
更新:
我喜欢下面列出的解决方案,但是如何将reducer扩展为包含ui reducer的类型.
combineReducers({ home: {createUiReducer('home',initialState),...home} })
这样,您可以使用基于嵌套域的ui而无需重复所有操作.不知道你会怎么做,因为你基本上是动态添加CASE语句.
那么你需要用前缀命名它们.如果你像大多数开发人员一样懒惰,那么创建一个帮助函数,它将为你生成reducer;)
原文链接:/react/301000.html像这个..
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"}