繁体   English   中英

ES6对象命名空间

[英]ES6 object namespacing

我遇到了一些我以前没见过的语法。 当我处理对象和使用React时,你可以通过这样做来简化命名空间

let {someProp} = prevProps

这样做可以让我每次想要使用时都避免编写prevProps.someProp

我不明白的是这种语法

let {someProp: oldData} = prevProps

console.log(someProp)将显示的值prevPros.someProp哪里 oldData从来???

此行上方的console.log(olddata)将显示undefined但下面的console.log(oldData)将显示以前的props。

let {someProp: myAlias} = prevProps

此语法允许您使用别名,例如您可以在代码中使用myAlias ,而不是someProp ,它被称为Object destructuring

正如@FelixKling的评论所述, 这里是官方参考

提供的链接示例:

let o = {p: 42, q: true};
let {p: foo, q: bar} = o;

console.log(foo); // 42 
console.log(bar); // true

是:

let {someProp} = prevProps

类似于:

let someProp = prevProps.someProp;

还有这个:

let {someProp: oldData} = prevProps

会是这样的:

let oldData = prevProps.someProp

看看这个链接

基本上你是在解构 prevProps,在这种情况下, oldData现在将具有someProp的值

这种语法是ES6中称为对象解构的闪亮新东西之一。

这是一个关于如何以不同方式使用解构的详细示例

const person = {
  first: 'Jack',
  last: 'Daniels',
  address: {
    city: 'Dallas',
  }
};

// destructure as it is
const { first, last } = person;

// destructure with custom name
const { first: firstName, last: lastName } = person;

// destructure with default value
const { first, last, middle = 'The Boss' } = person;

// destructure with custom name and default value
const { first, last, middle: middleName = 'The Boss' } = person;

// destructure nested keys
const { first, last, address: { city } } = person;

// destructure nested keys with custom name
const { first, last, address: { city: myCity } } = person;

// destructure nested keys safely
const { first, last, address: { city } = {} } = person;

// destructure rest of the values
const { first, ...rest } = person; // => rest will have all keys but first

暂无
暂无

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

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