如何修改复杂嵌套对象数组的深层属性并避免ESLint嵌套三元规则报错
深层嵌套数组属性修改的优化方案
针对你需要消除嵌套三元语法、同时实现不可变更新的需求,有几种更简洁的实现方案:
方案1:直接简化逻辑消除嵌套三元
你当前需要实现的是0和1的状态翻转,不需要嵌套判断,直接用算术运算即可实现,修改后仅保留一层三元,完全符合ESLint的no-nested-ternary规则,代码改动最小:
toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) { return state.map((opticalHeadUnit) => opticalHeadUnit.name === payload.opticalHeadUnitName ? { ...opticalHeadUnit, detectors: opticalHeadUnit.detectors.map( (detector, index) => ({ ...detector, status: { ...detector.status, value: index === payload.index ? 1 - detector.status.value : detector.status.value, }, }), ), } : opticalHeadUnit, ); }
注:原代码最外层的数组展开[...state.map()]属于冗余写法,map本身就返回新数组,可以直接去掉。
方案2:抽离公共逻辑的优化版
你当前将判断逻辑抽离为独立函数的思路是合理的,符合单一职责原则,主流程可读性更高,可以进一步简化函数内的判断逻辑:
const getDetectorStatusValue = (index: number, targetIndex: number, detector: IDetector) => { if (index !== targetIndex) return detector.status.value return 1 - detector.status.value } toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) { return state.map((opticalHeadUnit) => opticalHeadUnit.name === payload.opticalHeadUnitName ? { ...opticalHeadUnit, detectors: opticalHeadUnit.detectors.map( (detector,index) => ({ ...detector, status: { ...detector.status, value: getDetectorStatusValue(index, payload.index, detector) }, }), ), } : opticalHeadUnit, ); }
方案3:用工具库简化深层不可变更新(适合高频嵌套修改场景)
如果项目中经常需要修改深层嵌套的状态,推荐使用Immer这类不可变更新工具,不需要手写多层展开运算符,代码和直接修改可变对象的写法一致,会自动生成新的不可变对象:
import produce from 'immer' toggleSwitchDetector(state: Array<IOpticalHeadUnit>, { payload }: any) { return produce(state, draft => { const targetUnit = draft.find(unit => unit.name === payload.opticalHeadUnitName) if (!targetUnit) return const targetDetector = targetUnit.detectors[payload.index] if (targetDetector) { targetDetector.status.value = 1 - targetDetector.status.value } }) }
内容的提问来源于stack exchange,提问作者Meyer Buaharon
相关产品推荐
相关产品推荐

