只需将您的主要状态划分为所需的多个向导状态,并随每个操作一起发送一个向导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,了解如何减少向导列表。
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: 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 };}


