【问题标题】:Creating variables for destructured objects in addition to their properties除了属性之外,还为解构对象创建变量
【发布时间】:2019-05-27 20:11:28
【问题描述】:

我有:

const { state: { mode } } = this

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

我也想声明state 变量。

有没有办法在不将其分解为两个语句的情况下对其进行解构?

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

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    当然,只需使用逗号,就好像您正在破坏父对象的另一个属性:

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

    请注意,这看起来与 not the same 非常相似,但您可能已经看到了以下 import 语法:

    import React, { Component } from 'react'
    

    这里,括号中的变量是命名的exports,而plain变量是默认的exports,与嵌套对象完全不同。

    【讨论】:

      【解决方案2】:

      您也可以将state 解构为变量:

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

      【讨论】:

        【解决方案3】:

        虽然这里的所有其他答案都建议使用一个词来获取值,但我添加这个答案是为了解释为什么我们只获得最深的嵌套值

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

        当您进行嵌套破坏时,您将遵守这样的规定

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

        它不是为每个属性创建一个单独的变量,

        【讨论】:

          猜你喜欢
          • 2022-08-23
          • 1970-01-01
          • 2014-05-30
          • 2019-10-02
          • 2016-06-15
          • 1970-01-01
          • 2019-09-18
          • 1970-01-01
          • 2013-09-22
          相关资源
          最近更新 更多