【问题标题】:Error when I return an object by an inline function call into another object in ES6/Reactjs当我通过内联函数调用将对象返回到 ES6/Reactjs 中的另一个对象时出错
【发布时间】:2019-01-25 12:46:21
【问题描述】:

当尝试从 React 应用程序中的函数/方法调用返回包含对象的对象时,我得到:

Syntax error: this is a reserved word

导致这个错误的代码是:

const object = {
                this.methodOne(),
                this.methodTwo(),
                this.methodThree()
                };

我想将对象返回到一个对象中,但语法错误似乎没有识别出我正在尝试调用这些函数来创建对象,例如:

methodOne(){
    return {foo: "bar"}
}

与我的班级分开的函数也会出现同样的问题。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 es6-class


    【解决方案1】:

    答案很简单。如果您不想使用对象键声明它们,而是希望它们使用它们直接在对象中返回的键值对,则必须使用扩展运算符:

    const object = {
                    ...this.methodOne(),
                    ...this.methodTwo(),
                    ...this.methodThree()
                        };
    

    这个 ES6 符号告诉 JavaScript 使用对象中的键/值对来返回对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 2022-11-21
      • 2018-12-29
      • 2018-07-27
      相关资源
      最近更新 更多