简体   繁体   中英

React — Syntax error: Unexpected token, expected ;

For some reason that I can't figure it out I am getting a syntax error in the following React component. The error is in the first curly bracket on the renderItem() . What's wrong?

Thank you in advance.

import _ from 'lodash';
import React from 'react';
import { ToDoListHeader } from './todo-list-header';
import { ToDoListItem } from './todo-list-item';

export const ToDoList = (props) => {
  renderItems() {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

  return (
    <div>
      <table>
        <ToDoListHeader />
        <tbody>
          {/* {this.renderItems()} */}
        </tbody>
      </table>
    </div>
  );
}

Well, you are getting error because you are defining the function like in a class, not in a function. Use a proper function declaration.

export const ToDoList = (props) => {
  const renderItems = () => {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

  return (
    <div>
      <table>
        <ToDoListHeader />
        <tbody>
          {/* {this.renderItems()} */}
        </tbody>
      </table>
    </div>
  );
}

It would work fine, if only ToDoList was a class, though.

  renderItems = () => {
    return _.map(this.props.todos, (todo, index) => <ToDoListItem key={index} {...todo} />)
  }

Your varian will work with es6 classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM