只需将您的主状态划分为所需数量的向导状态,并随每个操作发送一个向导 ID,以便您的减速器知道要处理哪一个。
As Array
{
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
属性对此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
};
}