ES6 中嵌套解构如何工作?

问题描述 投票:0回答:5

我知道这可能是一个非常基本的问题,但我不精通 ES6 并且我遇到过这种语法:

const { rootStore: { routerStore } } = this.props;

我明白这样的意思:

const { rootStore } = this.props;

(从

rootStore
中的属性
rootStore
创建 const
this.props
)。

但是上面的双重解构(我认为是解构)是什么意思?

javascript ecmascript-6 destructuring
5个回答
68
投票

这称为嵌套解构,在很多情况下都非常有用。

让我们一点一点来理解吧。

看这个例子:

const person = {
    friend: {
        name: 'john',
        age: 20,
    },
};

const { friend } = person;

console.log(friend);

这里我们使用解构得到了 prop

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

漂亮!!

如果您想了解更多有关解构的信息,请查看这些资源:

解构赋值 MDN

ECMAScript 6 中的解构和参数处理


5
投票

const { rootStore: { routerStore } } = this.props;

补充一下我的部分,上面的代码实际上意味着以下内容

const { routerStore } = this.props.rootStore;

不是以下内容:

const {rootStore} = this.props
const {routerStore} = rootStore

区别在于,第一个仅定义了一个常量

routerStore
,而第二个则定义了两个常量
rootStore
routerStore
。所以差别很小。


5
投票

这意味着

const {rootStore} = this.props
const {routerStore} = rootStore

除了第一行不会生效,即

rootStore
不会被定义。


1
投票

在解构一个对象时,冒号左边的部分是属性名,右边的部分是属性值被解构成的内容。 (简写的工作方式与对象字面量相同,其中

{ x }
相当于
{ x: x }
。)根据解构出现的位置来声明或分配该目标:

const { x: y } = z;
// equivalent to:
const y = z.x;
let { x: y } = z;
// equivalent to:
let y = z.x;
({ x: y }) = z;
// equivalent to:
y = z.x;

其中

y
可以是另一种模式。所以这个:

const { rootStore: { routerStore } } = this.props;

相当于:

const { routerStore } = this.props.rootStore;

如果只使用一个属性,我也会这样写。如果有帮助的话,您可以将冒号读作“进入”。


0
投票

它将

routerStore

分开
this.props.rootStore.routerStore

通过使用嵌套对象进行解构赋值

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.