【问题标题】:What will be equivalent of following code in es5?什么将相当于 es5 中的以下代码?
【发布时间】:2016-11-15 01:53:35
【问题描述】:

es5 中的以下代码相当于什么?

constructor(props) {
  super(props);

  this.state = { ...this.props };
}

【问题讨论】:

  • this.state = Object.assign({}, this.props)
  • 我认为 Object.assign 仍然算作 es6。 ecma-international.org/ecma-262/6.0/#sec-object.assign。使用 es5,您只需复制所有内容或在下划线或 lodash 中使用助手
  • 你总是可以让 Babel 把它编译成 ES5 代码,看看它做了什么。
  • @chenkehxx:它有效,谢谢!另外,我将如何在 es5 中编写这个? this.state = { editFlag : false, ...this.props }
  • @BhushanLodha 应该是this.state = Object.assign({editFlag: false}, this.props),或者this.state=_.extend({editFlag: false}, this.props) 更容易理解。

标签: reactjs ecmascript-6 ecmascript-5


【解决方案1】:

如果不使用任何 >= ES6 语法,该代码将看起来像这样。

function MyComponent(props) {
  // super(props)
  React.Component.call(this, props);

  // this.state = { ...this.props };
  this.state = Object.assign({}, props);
}

Babel 的网站has a repl,您可以使用它来查看编译后的代码究竟是什么样子。

在这种情况下 it's quite complex 因为它主要包含在 Babel 用于为 ES5 填充 ES6 类的类实用程序中。


this.state = { editFlag : false, ...this.props } 的第二个例子类似。

this.state = Object.assign({}, editFlag: false, this.props);

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多