Creating variables for destructured objects in add

2020-04-02 07:11发布

I have:

const { state: { mode } } = this

console.log(mode) //'mode'
console.log(state) //undefined

I want to declare the state variable as well.

Is there a way to destructure this without breaking it into two statements?

const { state } = this
const { mode } = state

3条回答
beautiful°
2楼-- · 2020-04-02 07:12

Sure, just use a comma as if you were destructing another property of the parent object:

const obj = { state: { mode: 'str' }};
const { state: { mode }, state } = obj;
console.log(mode);
console.log(state);

Note that this looks very similar to, but is not the same as the following import syntax you may have seen:

import React, { Component } from 'react'

Here, the variables in brackets are named exports, while the plain variable is the default export, which is entirely different from nested objects.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-02 07:15

You can destructure the state to a variable as well:

const { state, state: { mode } } = { state: { mode: 'mode' } };

console.log(mode) // 'mode'
console.log(state) // { mode: 'mode' }

查看更多
Anthone
4楼-- · 2020-04-02 07:24

While all the other answer here suggested a word around to get values, but i am adding this answer to explain why we getting only the deep most nested value

let state = {
    state: {
      mode : 'some value'
 }
}

const { state: { mode } } = state

When you do nested destructing you will be complied to something like this

var state = {
  state: {
    mode: 'some value'
  }
};
var mode = state.state.mode;  // this is how your de-structuring is interpreted 

It is not creating a separate variable for each of the property,

查看更多
登录 后发表回答