如何简化扩展语法es6

时间:2017-11-17 13:04:00

标签: javascript object ecmascript-6 spread-syntax

如何简化代码,我试着生成对象并调用每个更改方法并依赖于参数(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]))
            }}

1 个答案:

答案 0 :(得分:1)

你可以把重复的部分放在一个额外的对象文字中 - 就像你已经用{{1}}做的那样 - 并参考它。

{{1}}

当然还有避免重复的默认方法:将重复的代码放在一个函数中(可能带有不同细节的参数),并从多个地方调用它。