【问题标题】:ES6 destructure to "this"ES6 解构为“this”
【发布时间】:2019-09-19 04:18:09
【问题描述】:

尝试 ES6 解构。

我在 React 类构造函数中使用了这段代码:

let { class, ...rest } = props;

上面的代码有效。但我需要this.classthis.rest 中的变量。

我有这段代码,它可以工作:

let { classes, ...rest } = props; 
this.classes = classes; 
this.rest = rest; 

我正在寻找这样的东西:

{ this.classes, ...this.rest } = props;  

【问题讨论】:

  • 您使用的是函数式组件还是类组件?也不是很清楚你想要完成什么
  • 我正在使用 react 类组件
  • 我想不出一种特别优雅的单行方式来做到这一点,但你可以Object.assign(this, { classes, rest })Object.assign(this, { rest: { ...props }, classes: props.classes })
  • 您的做法和@rayhatfield 建议的方式是正确的。但是我觉得可能不需要将 props 复制到类变量,因为您可以在任何需要的地方从 props 访问它们
  • 请记住,可读、易于理解的代码比节省输入的几个字符更重要。首先要清楚。

标签: javascript reactjs ecmascript-6 destructuring


【解决方案1】:

您可以使用重命名属性,但不幸的是它涉及到一些重复:

({ classes: this.classes, ...this.rest } = props);

classes 是我们要离开props 的属性的名称; this.classes 是分配给它的变量的名称。有了this.rest,我们显然不需要命名原来的属性名了。

演示:

function Foo(props) {
    ({ classes: this.classes, ...this.rest } = props);
}

const props = {
  classes: 'some clases',
  a: 'A',
  b: 'B'
}

console.log(new Foo(props));

【讨论】:

  • 该死,这更干净+1
  • 整洁,但我很矛盾是否需要相当高级的理解水平才能遵循它正在做的事情实际上是更好的代码。
  • @jfriend00:我可以看到你反对的观点,例如!!~...indexOf成语;但这并不完全是代码高尔夫,它只是使用现代 ES 解构语法。我不会称它为“高级”,只不过是使用Setclass
【解决方案2】:

实现的一个更棘手的方法是使用与所需 this 绑定的函数

这里重命名是关键,这里发生的是它从props 中选择值并将其分配给我们重命名的任何内容

({ classes:this.classes,...this.rest } = props)

所以这实际上和

一样
this.classes = props.classes;
this.rest = all the properties expect those which are already destrucutred

您可以在此处粘贴您的代码并查看简化版Babel


const props = {
  classes: 'some clases',
  a: 'A',
  b: 'B'
}

let tempThis = {}
console.log(tempThis)

let getMeValuesOnThis = function(props) {
  ({ classes:this.classes,...this.rest } = props)
}.bind(tempThis)

getMeValuesOnThis(props)

console.log('---values after function execution---')
console.log(tempThis)

ray 已经建议了一种在 cmets 中使用 Object.assign 的方法

【讨论】:

  • 您对bind 的建议没有任何意义。如果您的示例中的this 是窗口对象,则输出为“正确”,但不是由于bind,您可以删除bind 并获得相同的输出。
  • @t.niese 好吧,你是对的,但同样可以在 this 可能与 window 对象不同的任何范围内完成,不是吗?
  • 我投了反对票,我已经说过bind 在这里没有任何意义。 .bind(this) 对变量 classesrest 的查找没有任何影响。在您的示例中写入 bind({}) 将导致完全相同的结果。 bind 仅对该函数中的 this 有影响,但对其他变量的查找没有影响,并且该函数中没有使用 this
  • @t.niese 哦,明白了,感谢您的指出,我感谢您的 cmets,已更新 :)
猜你喜欢
  • 2019-11-19
  • 2018-05-04
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 2019-05-28
相关资源
最近更新 更多