代码之家  ›  专栏  ›  技术社区  ›  Radex

解构对象-如何以更简洁的方式重写

  •  1
  • Radex  · 技术社区  · 8 年前

    我想知道是否有可能简化此代码并将其写在一行中(我甚至可以使用ES6-7)

    const { dimensions } = this.state
    const { height} = dimensions
    console.log(height)
    
    1 回复  |  直到 8 年前
        1
  •  8
  •   Ori Drori    8 年前

    你可以 destructure a nested structure .

    分解内部属性-高度:

    const state = { dimensions: { width: 200, height: 100 }}
    
    const { dimensions: { height } } = state
    
    console.log(height)

    分解外部和内部特性-尺寸和高度:

    const state = { dimensions: { width: 200, height: 100 }}
    
    const { dimensions, dimensions: { height } } = state
    
    console.log(dimensions)
    console.log(height)