ES6 双重解构

ES6 double destructure

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

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

我明白这样的意思是什么:

const { rootStore } = this.props;

(从 this.props 中的 属性 rootStore 创建一个 const rootStore

但是上面的双重解构(我假设是解构)是什么意思呢?

意思是

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

除了第一行不会生效,即rootStore不会被定义。

它将 routerStore

分开
this.props.rootStore.routerStore

通过获取 destructuring assignment 的嵌套对象。

解构对象时,冒号左边的部分是属性名称,右边的​​部分是属性值被解构成的内容。 (Shorthand 的工作方式与它在对象字面量中的作用相同,其中 { 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;

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

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

补充一下我的部分,上面的代码实际意思如下

const { routerStore } = this.props.rootStore;

不是以下内容:

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

区别在于第一个只定义了一个常量routerStore,而第二个定义了两个常量rootStorerouterStore。所以差别不大。

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

让我们一点点了解,

看这个例子

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 的值,这在您有嵌套对象的许多情况下很有用,在上面的代码中,如果您尝试记录朋友的价值你会得到 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

漂亮!!

如果您想了解有关解构的所有信息,请查看此资源

Destructuring assignment MDN

Destructuring and parameter handling in ECMAScript 6