繁体   English   中英

这里如何使用解构?

[英]How to use destructuring here?

这里我不明白为什么ESlint不允许这个赋值,请帮忙。

我在这里看到了这段代码: https : //styled-system.com/responsive-styles

export const breakpoints = [512, 768, 1024, 1280]

breakpoints.sm = breakpoints[0]
breakpoints.md = breakpoints[1]
breakpoints.lg = breakpoints[2]
breakpoints.xl = breakpoints[3]

你可以像这样解构它。

 const breakpoints = [{ id: 1, size: 512 }, {id: 2, size: 768}, { id: 3, size: 1024 }, { id: 4, size: 1280}] const breakpointsOriginal = [512, 768, 1024, 1280] const [sm, md, lg, xl] = breakpoints; // You can use it like sm.size and the sm.size value is = 512 const [small, medium, large, extra_large] = breakpointsOriginal; // You can use small and the small value = 512

export const breakpoints = [512, 768, 1024, 1280];

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

使用以下代码在JSFiddle对其进行了测试:

const breakpoints = [512, 768, 1024, 1280];

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

console.log(breakpoints.sm);
console.log(breakpoints.md);
console.log(breakpoints.lg);
console.log(breakpoints.xl);

对我来说效果很好。 请注意,我需要删除 JSFiddle 中的export ,还需要添加分号才能正常工作。

编辑:

我无法判断您的实际场景,但我个人会尽量避免使用此类附加属性扩展数组对象,除非我确实需要根据场景通过属性名称和数组索引访问这些断点。

由于我通常只需要一个策略(数组索引或对象属性),因此我会创建一个“常规”对象并向其添加四个属性。

我可以使用数组解构来初始化这些属性:

const bpArr = [512, 768, 1024, 1280];
const breakpoints = {};

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = bpArr;

但是,如果已经没有包含断点数值的源数组,我将简单地为断点使用对象字面量,这更简单易读:

const breakpoints = {
  sm: 512,
  md: 768,
  lg: 1024,
  xl: 1280
};

最终由您来保持代码尽可能清晰和简单,并仅在必要时使其复杂。 ;)

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

这将不起作用,因为您不能混合解构和分配。

尝试这个:

[sm, md, lg, xl] = breakpoints;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM