销毁嵌套对象:如何获得父级及其子级值?

时间:2019-02-08 11:19:33

标签: javascript reactjs destructuring react-ref

在下面的函数中,我得到具有属性current的textarea对象。

在这里,嵌套解构可与StartEnd变量一起使用。但是current变量不起作用。

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

    // do something with current, Start, and End
}

3 个答案:

答案 0 :(得分: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;

被交易到:

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

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

如您所见,未创建current变量。

答案 1 :(得分: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
}

答案 2 :(得分: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
      }

如果您不想将默认值分配给current,但仍想使用该变量,则只需写属性名称即可,无需分配。当使用空对象调用 someFunction 时,如果不将默认值分配给current,则它将是未定义的。

    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