这里给出的所有解决方案都是正确的。
最简单的更改是将函数调用包装在 JSX 元素中:
return (
<div>
{ this.renderRecipeItems() }
</div>
)
然而,没有一个答案(正确地)告诉您代码首先被破坏的原因。
为了更简单的示例,让我们稍微简化一下代码
// let's simplify this
return (
{ this.renderRecipeItems() }
)
使得含义和行为仍然相同。 (删除括号并移动花括号):
// into this
return {
this.renderRecipeItems()
};
这段代码的作用是它包含一个块,表示为{}
,您尝试在其中调用一个函数。
因为return https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return语句、块{}
被视为对象字面量 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals
对象字面量是对象的零对或多对属性名称和关联值的列表,括在大括号 ({}) 中。
期望a: b
or a
(速记 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) 属性值对的语法。
// valid object
return {
prop: 5
}
// also valid object
const prop = 5;
return {
prop
}
但是,您传递的是函数调用,这是无效的。
return {
this.renderRecipeItems() // There's no property:value pair here
}
当执行此代码时,引擎假设它将读取对象文字。当它达到this.
,它注意到.
不是属性名称的有效字符(除非您将其包装在字符串中 - 见下文),并且执行在此处中断。
function test() {
return {
this.whatever()
// ^ this is invalid object-literal syntax
}
}
test();
为了演示,如果您将函数调用括在引号中,代码将接受.
作为属性名称的一部分,现在会因为未提供属性值而中断:
function test() {
return {
'this.whatever()' // <-- missing the value so the `}` bellow is an unexpected token
}
}
test();
如果您删除return
语句,代码不会中断,因为那只是一个函数调用block https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block:
function test() {
/* return */ {
console.log('this is valid')
}
}
test();
现在,另一个问题是,编译代码的不是 JS 引擎,而是,这就是为什么你得到this is a reserved word
错误而不是Uncaught SyntaxError: Unexpected token .
.
原因是 JSX 不接受 JavaScript 语言的保留字,例如class
and this
。如果您删除this
,你可以看到- babel 尝试将代码解析为具有属性但没有值的对象文字,这意味着 babel 会看到以下内容:
return {
'renderRecipeItems()' // <-- notice the quotes. Babel throws the unexpected token error
}