解构嵌套对象:如何让家长和它的孩子价值观?

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

在下面的功能,我得到的财产current textarea的对象。

在这里,嵌套的解构与工作和Start变量End。但current变量不起作用。

function someFunction({ current: { selectionStart: Start, selectionEnd: End } }, AppStateSetter) {

    // do something with current, Start, and End
}
javascript reactjs destructuring react-ref
3个回答
9
投票

第一个解构只创建StartEnd变量。如果你想创建current作为一个变量,那么你就需要再次声明。

function ({ current: { selectionStart: Start, selectionEnd: End }, current }, AppStateSetter) {

// do something with current , Start , and End

}

您可以test it on the Babel compiler

此代码:

const object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
}

const { current: { selectionStart: Start, selectionEnd: End } } = object;

获取transpiled到:

var object = {
  current: {
    selectionStart: "prop 1",
    selectionEnd: "prop2"
  }
};

var _object$current = object.current,
    Start = _object$current.selectionStart,
    End = _object$current.selectionEnd;

正如你所看到的,是不是创造了current变量。


2
投票

我认为,当电流undefined你所面临的问题发生。

你可以尝试用默认值解构。

function ({ current: { selectionStart: Start, selectionEnd: End } = {} }, AppStateSetter) {
  // do something with Start and End
}

如果你认为你需要访问current为好,尽量在函数内部解构。

function ({ current = {}}, AppStateSetter) {
  const { selectionStart: Start, selectionEnd: End } = current
  // do something with current, Start and End
}

0
投票

您可以解构并在一个声明中指定默认值。

function someFunction({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current = {}
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current,
      // with current's default value set to empty object
      }

如果您不想默认值分配给电流,但仍希望使用该变量,你可以随便写,没有分配的属性的名称。当someFunction被称为空的对象,如果你没有一个默认值分配给当前这将是不确定的。

    function someFunction1({
        current: {
          selectionStart: Start,
          selectionEnd: End
        } = {},
        current
      },
      AppStateSetter) {
      // now you can use the let variables Start, End and current
      // if empty object is passed, current will be undefined
    }

的jsfiddle片段:Nested object destructuring with and without default values

© www.soinside.com 2019 - 2024. All rights reserved.