我知道这可能是一个非常基本的问题,但我不太精通ES6,我遇到过这样的语法:
const { rootStore: { routerStore } } = this.props;
我明白这意味着什么:
const { rootStore } = this.props;
(从rootStore
中的属性rootStore
创建const this.props
)。
但是,上述双重解构(我认为是解构)意味着什么?
发布于 2018-06-23 10:11:07
这被称为嵌套析构,在许多情况下非常有用。
让我们一点一点地理解它。
请看下面的示例:
const person = {
friend: {
name: 'john',
age: 20,
},
};
const { friend } = person;
console.log(friend);
在这里,我们得到了使用析构的支柱friend
的值。因为值本身是一个对象,所以我们也可以使用对它的析构。
在前面的示例中:
const person = {
friend: {
name: 'john',
age: 20,
},
};
const { friend } = person;
console.log(friend);
const {age} = friend ;
console.log(age) ;
现在,我们也可以使用析构来获得age
道具,这非常实用,但是如果我只需要age
道具,而我不需要friend
道具呢?我能在一步之内完成以上所有的例子吗?是的!!这就是ES6的惊人之处:
const person = {
friend: {
name: 'john',
age: 20,
},
};
const { friend :{age} } = person;
console.log(age);
正如您所看到的,我们在一个步骤中获得age
的值,当您有嵌套对象时,这在很多情况下都是有用的。在上面的代码中,如果尝试记录friend
的值,就会得到ReferenceError: friend is not defined
。
你知道吗?你可以使嵌套破坏的深度,你想。看看这个复杂的例子,这只是为了好玩。
const person = {
friend: {
name: 'john',
other: {
friend: {
name: {
fullName: {
firstName: 'demo',
},
},
},
},
},
};
const {
friend: {
other: {
friend: {
name: {
fullName: { firstName },
},
},
},
},
} = person;
console.log(firstName); // demo
漂亮!!
如果您想了解更多关于销毁的知识,请查看以下资源:
ECMAScript 6中的分解和参数处理
发布于 2018-06-23 09:56:17
这意味着
const {rootStore} = this.props
const {routerStore} = rootStore
但第一行不会生效,即rootStore
不会被定义。
发布于 2018-06-23 10:10:17
const { rootStore: { routerStore } } = this.props;
仅仅为了添加我的部分,上面的代码实际上意味着
const { routerStore } = this.props.rootStore;
不是下列情况:
const {rootStore} = this.props
const {routerStore} = rootStore
区别在于,第一个只定义一个常量routerStore
,而第二个定义两个常量rootStore
和routerStore
。所以没有什么区别。
https://stackoverflow.com/questions/50999968
复制相似问题