当我 return 一个对象通过内联函数调用 ES6/Reactjs 中的另一个对象时出错
Error when I return an object by an inline function call into another object in ES6/Reactjs
在 React 应用程序中尝试 return 包含来自 function/method 调用的对象的对象时,我得到:
Syntax error: this is a reserved word
导致此错误的代码是:
const object = {
this.methodOne(),
this.methodTwo(),
this.methodThree()
};
我想将 return 个对象合并为一个对象,但语法错误似乎无法识别我正在尝试调用这些函数来创建对象,例如:
methodOne(){
return {foo: "bar"}
}
与我的 class 不同的函数也会出现同样的问题。
答案很简单。如果您不想使用对象键来声明它们,而是希望它们使用它们直接在对象中返回的键值对,则必须使用扩展运算符:
const object = {
...this.methodOne(),
...this.methodTwo(),
...this.methodThree()
};
这个 ES6 表示法告诉 JavaScript 将对象中的 key/value 对用于返回的对象。
在 React 应用程序中尝试 return 包含来自 function/method 调用的对象的对象时,我得到:
Syntax error: this is a reserved word
导致此错误的代码是:
const object = {
this.methodOne(),
this.methodTwo(),
this.methodThree()
};
我想将 return 个对象合并为一个对象,但语法错误似乎无法识别我正在尝试调用这些函数来创建对象,例如:
methodOne(){
return {foo: "bar"}
}
与我的 class 不同的函数也会出现同样的问题。
答案很简单。如果您不想使用对象键来声明它们,而是希望它们使用它们直接在对象中返回的键值对,则必须使用扩展运算符:
const object = {
...this.methodOne(),
...this.methodTwo(),
...this.methodThree()
};
这个 ES6 表示法告诉 JavaScript 将对象中的 key/value 对用于返回的对象。