假设我有一个可重复使用的容器。这是一个具有多个页面的向导。
向导状态由redux / actions驱动。当一个动作被触发时,我使用一个reducer来更新我的状态。
如果我想复制多个向导并使用自己的状态怎么办?
我认为必须有一种方法可以使某个动态化简器(可以创建/销毁)来处理动作,然后使每个单独的向导从这些动态的存储状态中被驱动。
推荐这个吗?是否有图书馆使这更容易?
只需将您的主要状态划分为所需的多个向导状态,并随每个操作一起发送一个向导ID,以便您的reducer知道要解决的状态。
{ wizards: [ { id: 'A', state: true }, { id: 'B', state: false }, { id: 'C', state: true } ] }
您可以编写一个向导精简器,该精简器了解如何精简单个向导状态。
function wizardReducer(wizard, action) { switch(action) { case 'TOGGLE': return { id: wizard.id, state: !wizard.state }; default: return wizard; } }
然后编写一个wizardsReducer,了解如何减少向导列表。
wizardsReducer
function wizardsReducer(wizards, action) { return wizards.map(function(wizard) { if(action.id == wizard.id) { return wizardReducer(wizard, action); } else { return wizard; } }); }
最后,使用combineReducers来创建根简化程序,该wizards属性将对此属性的责任委派给this wizardsReducer。
combineReducers
wizards
combineReducers({ wizards: wizardsReducer });
如果要将向导存储在一个对象中,则必须以wizardsReducer稍微不同的方式构造。
{ wizards: { A: { id: 'A', state: true }, B: { id: 'B', state: false }, C: { id: 'C', state: true } } }
映射状态并没有多大意义,当我们可以直接选择需要的状态时。
function wizardsReducer(wizards, action) { if(!(action.id in wizards)) return wizards; const wizard = wizards[action.id]; const updatedWizard = wizardReducer(wizard, action); return { ...wizards, [action.id]: updatedWizard }; }