为什么我的React组件中出现了意外的令牌?

Vla*_*vić 1 javascript ecmascript-6 reactjs

我有一个问题,我无法弄清楚如何解决它.我已经检查了React文档,我的语法与Facebook官方文档中的语法类似.

我刚开始学习React库,学会了如何使用道具但是状态我有问题.此代码抛出一个错误,表示逗号字符不属于那里,而在文档中存在逗号.如果我删除了逗号,那么它说todos is undefined:

class App extends Component {
  // State
  getInitialState() {
      return (
        todos: ["Wake up early", "Do some body exercise", "Continue learning React"]
      )
  }, <-- This is making the problem and it can't compile 
  // Props
  render () {
    return (
      <div id ="todo-list">
       <h1>Helo, user</h1>
       <p>Things to do:</p>
       <ul>
        <li>{this.state.todos[0]}</li>
        <li>{this.state.todos[1]}</li>
        <li>{this.state.todos[2]}</li>
       </ul>
      </div>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)

我正在学习这个教程的YouTube链接,到目前为止他的教程,但我遇到了这个错误,我不知道该怎么做.

Li3*_*357 5

您正在尝试使用ES5语法在ES2015类中创建组件,但这种方法无法解决问题.使用ES2015类定义组件时存在一些关键差异.

在ES2015类中,方法之间没有逗号,您可能会将它与对象文字混淆.

此外,在ES2015类中,您必须使用constructor设置初始状态,而不是getInitialState.那是ES5的createClass.当创建组件的新实例并"构造组件"时,将调用构造函数,其作用类似于componentWillMount方法.这是ES2015课程中的"保留"方法.以下是如何使用constructor:

constructor() {
    super(); //super before anything else to call superclass constructor
    this.state = {
        todos: ["Wake up early", "Do some body exercise", "Continue learning React"]
    };
}
Run Code Online (Sandbox Code Playgroud)

这将this.state直接设置对象(仅在构造函数中执行此操作!)todos未定义的原因是因为与ES2015的React不像getInitialState在ES5 中那样使用.因此,您从未真正设置状态并且todos未定义.

注意:不要在React组件中使用ID.React组件意味着可重用,如果您不能拥有两个具有相同ID的元素.