对象解构并立即返回

时间:2017-09-15 09:29:14

标签: javascript react-redux

从对象中销毁道具并立即返回它是正确的: const mapStateToProps = state => ({ ...{ name, phone, shift} = state.employeeForm });

工作得很好,但我的IDE很生气。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

看起来很不错。由于javascript语法正在快速发展并提供大量语法变体,因此IDE仍在追赶。

答案 1 :(得分:0)

如何通过函数的参数对其进行解构? Spread运算符也会捕获irrelevant键,基本上它会创建对象的副本:

//编辑:添加了两个解构示例,我还发现你的扩展运算符函数由于某种原因将变量泄漏到全局命名空间,至少在这里是SO片段:

let state = {
  form: {
    name: 'test',
    phone: 123,
    shift: true,
    irrelevant: false,
  }
};

(function () {
  let fun2 = ({form: {name, phone, shift}}) => ({name, phone, shift});
  console.log('fun2', fun2(state));
})();

try {
  console.log(name, phone, shift);
} catch (e) {
  console.log('no leak');
}

(function () {
  let fun3 = state => {
    let {name, phone, shift} = state.form;
    return {name, phone, shift};
  };
  console.log('fun3', fun3(state));
})();

try {
  console.log(name, phone, shift);
} catch (e) {
  console.log('no leak');
}

(function () {
  let fun = state => ({
    ...{name, phone, shift} = state.form
  });
  console.log('fun', fun(state));
})();

try {
  console.log('leak:', name, phone, shift);
} catch (e) {
  console.log('no leak');
}