我在前端有一个初始静态模型。看起来像这样:
[
{
completed: false,
id: 0,
index: 0,
isNavigationAllowed: true,
name: 'Test1',
},
{
completed: false,
id: 1,
index: 1,
isNavigationAllowed: false,
name: 'Test2',
},
{
completed: false,
id: 2,
index: 2,
isNavigationAllowed: false,
name: 'Test3',
},
]
简而言之,我的应用程序的行为就像一个向导页面,因此当用户单击“下一步”按钮时,我应该更改模型(并且不要对其进行突变)。我使用以下转换函数:
function transformWizardStepsModelForNext(step, wizardStepsModel) {
return wizardStepsModel.reduce((accumulator, currentValue) => {
if (step === currentValue.index) {
let newValue = { ...newValue }
newValue.completed = true
newValue.isNavigationAllowed = false
return [...accumulator, newValue]
}
return [...accumulator, currentValue]
}, [])
}
我应该在每个用户的“下一个”和“上一个”按钮单击时更改模型中的两个对象(无突变)。因此,在第一次单击后,我应该更改:completed = true,第一个对象的isNavigationAllowed = false字段,以及第二个对象的isNavigationAllowed = true字段。逻辑相同,但单击“上一个”按钮则相反。我选择了reduce数组方法进行此转换,但是看来我只能使用一个对象。问题是:从您的角度来看,最有效的转换方式是什么?
答案 0 :(得分:0)
您可以使用地图功能而不是reduce
wizardStepsModel.map(currentValue => {
if (step === currentValue.index) {
return {
...currentValue,
completed: true,
isNavigationAllowed: false
}
} else if (step + 1 === currentValue.index) {
return {
...currentValue,
isNavigationAllowed: true
}
}
else return currentValue
})