Javascript React.js - 语法错误:这是 render() 函数中的保留字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44849206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:45:44  来源:igfitidea点击:

React.js - Syntax error: this is a reserved word in render() function

javascriptreactjsbabel

提问by Nickadiemus

I'm stuck on a error for the reserved keyword "this". In my React Component below shows me passing in a state from a my main component "App.js" to my "RecipeList.js" component to then map the data and render each RecipeItem Component. I just don't understand why I get this error

我遇到了保留关键字“this”的错误。在下面的 React 组件中,我将一个状态从我的主要组件“App.js”传递到我的“RecipeList.js”组件,然后映射数据并呈现每个 RecipeItem 组件。我只是不明白为什么我会收到这个错误

React.js - Syntax error: this is a reserved word

React.js - 语法错误:这是一个保留字

The error is called in RecipeList inside the render return method; If anybody could help that would great!

该错误在渲染返回方法内的 RecipeList 中调用;如果有人可以提供帮助,那就太好了!

Thanks

谢谢

App.js

应用程序.js

//main imports
import React, { Component } from 'react';

//helper imports
import {Button} from 'reactstrap'
import RecipeItem from './components/RecipeItem';
import RecipeList from './components/RecipeList';
import './App.css';

const recipes = [
  {
    recipeName: 'Hamburger',
    ingrediants: 'ground meat, seasoning'
  },
  {
    recipeName: 'Crab Legs',
    ingrediants: 'crab, Ole Bay seasoning,'
  }
];

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      recipes
    };
  }

  render() {
    return (
      <div className="App">
        <div className = "container-fluid">
          <h2>Recipe Box</h2>
          <div>
            <RecipeList recipes = {this.state.recipes}/>
          </div>
        </div>
        <div className = "AddRecipe">
          <Button>Add Recipe</Button>
        </div>

      </div>
    );
  }
}

export default App;

RecipeLists.js

食谱列表.js

import React, {Component} from 'react';
import _ from 'lodash';
import RecipeItem from './RecipeItem';


class RecipeList extends Component {

    renderRecipeItems() {
      return _.map(this.props.recipes, recipeItem => <RecipeItem key = {i} {...recipes} />);
    }

    render() {
      return (
        { this.renderRecipeItems() }
      );
    }
}

export default RecipeList

回答by nem035

All the solutions given here are correct.

这里给出的所有解决方案都是正确的。

The easiest change is to just wrap your function call in a JSX element:

最简单的更改是将您的函数调用包装在 JSX 元素中:

return (
  <div>
    { this.renderRecipeItems() }
  </div>
)

However, none of the answers are (correctly) telling you why the code was breaking in the first place.

但是,没有一个答案(正确)告诉您为什么代码首先被破坏。

For the sake of an easier example, let's simplify your code a bit

为了更简单的例子,让我们稍微简化一下你的代码

// let's simplify this
return (
  { this.renderRecipeItems() }
)

such that the meaning and behavior are still the same. (remove parenths and move curlies):

这样意义和行为仍然相同。(删除括号并移动卷曲):

// into this
return {
  this.renderRecipeItems()
};

What this code does is it contains a block, denoted by {}, within which you're trying to invoke a function.

这段代码的作用是它包含一个由 表示的块,{}您试图在其中调用一个函数。

Because of the returnstatement, the block {}is treated like an object literal

由于该return语句,块{}被视为对象文字

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}).

对象字面量是一个包含零对或多对属性名称和对象关联值的列表,用花括号 ({}) 括起来。

which expects either a: bor a(shorthand) syntax for it's property-value pairs.

它的属性值对需要a: bor a简写)语法。

// valid object
return {
  prop: 5
}

// also valid object
const prop = 5;
return {
  prop
}

However, you're passing a function call instead, which is invalid.

但是,您正在传递一个函数调用,这是无效的。

return {
  this.renderRecipeItems() // There's no property:value pair here
}

When going through this code, the engine assumes it will read an object-literal. When it reaches the this., it notices that .is not a valid character for a property name (unless you were wrapping it in a string - see bellow) and the execution breaks here.

在执行此代码时,引擎假定它将读取对象字面量。当它到达 时this.,它注意到这.不是属性名称的有效字符(除非您将其包装在字符串中 - 见下文)并且执行在此处中断。

function test() {
  return {
    this.whatever()
    //  ^ this is invalid object-literal syntax
  }
}

test();

For demonstration, if you wrapped your function call in quotes, code would accept the .as part of a property name and would break now because a property value is not provided:

为了演示,如果您将函数调用括在引号中,代码将接受.作为属性名称的一部分并且现在会中断,因为未提供属性值:

function test() {
  return {
    'this.whatever()' // <-- missing the value so the `}` bellow is an unexpected token
  }
}

test();

If you remove the returnstatement, the code wouldn't break because that would then just be a function call within a block:

如果删除该return语句,则代码不会中断,因为那将只是内的函数调用:

function test() {
  /* return */ {
    console.log('this is valid')
  }
}

test();

Now, an additional issue is that it's not the JS engine that is compiling your code but it's babel, which is why you get the this is a reserved worderror instead of Uncaught SyntaxError: Unexpected token ..

现在,另一个问题是编译您的代码的不是 JS 引擎,而是babel,这就是为什么您收到this is a reserved word错误而不是Uncaught SyntaxError: Unexpected token ..

The reason is that JSX doesn't accept reserved words from the JavaScript language such as classand this. If you remove this, you can see that the reasoning above still applies- babel tries to parse the code as an object literal that has a property, but no value, meaning babel sees this:

原因是 JSX 不接受来自 JavaScript 语言的保留字,例如classthis。如果您删除this,您可以看到上面推理仍然适用- babel 尝试将代码解析为具有属性但没有值的对象文字,这意味着 babel 会看到:

return {
  'renderRecipeItems()' // <-- notice the quotes. Babel throws the unexpected token error
}

回答by Chase DeAnda

You can avoid this by rewriting RecipeLists.jsas a pure stateless component.

您可以通过重写RecipeLists.js纯无状态组件来避免这种情况。

As Pure component:

作为纯组件:

import _ from 'lodash';
import RecipeItem from './RecipeItem';

const RecipeList = props => renderRecipeItems(props);

const renderRecipeItems = ({ recipes }) => _.map(recipes, recipeItem => <RecipeItem key = {i} {...recipes} />);

export default RecipeList;

So now you're component is basically just a function with params.

所以现在你的组件基本上只是一个带有参数的函数。

回答by Mayank Shukla

Wrap the this.renderRecipeItems()part with a div, it will work.

用 包裹this.renderRecipeItems()零件div,它将起作用。

Reason why it was failing, is explained extremely well by @nem035 in this answer.

@nem035 在这个答案中很好地解释了它失败的原因。

Like this:

像这样:

render () {
   return (
      <div>
         { this.renderRecipeItems() }
      </div>
   );
}

And i think instead of:

我认为而不是:

<RecipeItem key = {i} {...recipes} />

It should be:

它应该是:

<RecipeItem key = {i} {...recipeItem} />

These are the changes i can see, may be some others will be required also.

这些是我可以看到的更改,可能还需要其他一些更改。