如何简化扩展语法es6
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何简化扩展语法es6相关的知识,希望对你有一定的参考价值。
如何简化代码,我试着生成对象并调用每个更改方法并依赖于参数(newValues)我改变了一些字段,似乎我有重复的代码,如何避免这种情况?我应该使用一些更难的方法来避免扩展语法
const formName = {
fieldRange: 'miConfiguration.fieldRange',
defaultTimeout: 'miConfiguration.doorConfiguration.defaultTimeout',
standAlone: 'miConfiguration.doorConfiguration.standAlone',
overrideTimeout: 'miConfiguration.doorConfiguration.overrideTimeout',
inputMode: 'miConfiguration.doorConfiguration.inputMode',
stopMi: 'miConfiguration.doorConfiguration.stopMi',
activeLow: 'miConfiguration.doorConfiguration.activeLow',
enableDualTechnology: 'miConfiguration.enableDualTechnology',
passageName: 'miConfiguration.passageName',
}
let {fieldRange, defaultTimeout, standAlone, overrideTimeout, inputMode, stopMi, activeLow, enableDualTechnology, passageName} = formName
let configurationsMi = {
[passageName]: null,
[fieldRange]: null,
[activeLow]: false,
[standAlone]: null,
[defaultTimeout]: null,
[overrideTimeout]: null,
[inputMode]: null,
[stopMi]: null,
[enableDualTechnology]: false,
}
const defaultValues = {
[MiConfigurationTypes.AccessPointOnly]: {
...configurationsMi,
[fieldRange]: MiFieldRanges.Disabled,
},
[MiConfigurationTypes.WanderingDetection]: {
...configurationsMi,
[fieldRange]: MiFieldRanges.Small,
},
[MiConfigurationTypes.MuteWanderingDetection]: {
...configurationsMi,
[fieldRange]: MiFieldRanges.Small,
},
[MiConfigurationTypes.LockedWanderingControl]: {
...configurationsMi,
[fieldRange]: MiFieldRanges.Small,
[standAlone]: DoorStates.Locked,
[defaultTimeout]: '00:00:03',
[overrideTimeout]: '00:00:30',
[inputMode]: InputModes.NotUsed,
[stopMi]: false,
},
[MiConfigurationTypes.OpenWanderingControl]: {
...configurationsMi,
[fieldRange]: MiFieldRanges.Small,
[standAlone]: DoorStates.Locked,
[defaultTimeout]: '00:00:03',
[overrideTimeout]: '00:00:30',
[inputMode]: InputModes.NotUsed,
[stopMi]: false,
},
}
onChange={(e, newValue) => {
console.log(defaultValues)
Object.keys(defaultValues[newValue]).forEach(key => change(key, defaultValues[newValue][key]))
}}
答案
你可以把重复的部分放在一个额外的对象文字中 - 就像你已经用configurationsMi
做的那样 - 并参考它。
const configurationsWanderingControl = {
[fieldRange]: MiFieldRanges.Small,
[standAlone]: DoorStates.Locked,
[defaultTimeout]: '00:00:03',
[overrideTimeout]: '00:00:30',
[inputMode]: InputModes.NotUsed,
[stopMi]: false,
};
const defaultValues = {
…
[MiConfigurationTypes.LockedWanderingControl]: {
...configurationsMi,
...configurationsWanderingControl,
},
[MiConfigurationTypes.OpenWanderingControl]: {
...configurationsMi,
...configurationsWanderingControl,
},
};
当然,还有一种避免重复的默认方法:将重复的代码放在一个函数中(可能带有不同细节的参数),并从多个地方调用它。
以上是关于如何简化扩展语法es6的主要内容,如果未能解决你的问题,请参考以下文章