这里给出的所有解决方案都是正确的。
最简单的更改是将函数调用包装在JSX元素中:
return ( <div> { this.renderRecipeItems() } </div>)但是,没有一个答案(正确地)告诉您代码为何首先被破坏。
为了更简单的示例,让我们简化一下代码
// let's simplify thisreturn ( { this.renderRecipeItems() })这样含义和行为仍然相同。(移走双亲并移动冰壶):
// into thisreturn { this.renderRecipeItems()};该代码的作用是它包含一个用表示的块,
{}您试图在其中调用一个函数。由于该
return语句,该块
{}被视为对象文字对象文字是用花括号({})括起来的零对或多对属性名称和对象的关联值的列表。
它的“属性-值”对需要使用“
a: b或”
a(简写)语法。
// valid objectreturn { prop: 5}// also valid objectconst 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语句,代码不会中断,因为那将只是一个块内的函数调用:
function test() { { console.log('this is valid') }}test();现在,另一个问题是,编译代码的不是JS引擎,而是babel,这就是为什么收到
thisis a reserved word错误而不是的原因
Uncaught SyntaxError: Unexpected token .。
原因是JSX不接受来自Javascript语言(例如
class和)的保留字
this。如果删除
this,您会发现上面的推理仍然适用 -babel尝试将代码解析为具有属性但没有值的对象常量,这意味着babel会看到以下内容:
return { 'renderRecipeItems()' // <-- notice the quotes. Babel throws the unexpected token error}


