无法迭代 React 组件来创建 table。意外的标记

Can't iterate React component to create table. Unexpected token

我正在尝试使用 ReactJS 创建一个由 REST API 填充的 table。问题是我不知道我在使用 sintax 时做错了什么......我正在使用 ES6。

这是 FooTable:

import React from 'react'
import  Foo from './Foo'

export default class  FooTable extends React.Component {

  render() {
    return(
    <tr>
      <td>id</td>
      <td>name</td>
      <td>surname</td>
    </tr>
    { //<-- This is the marked error by webpack
      this.props. Foos.map( foo=>{
             return  < Foo key={foo.id} name={foo.name} surname={foo.surname}/>
      })
    }
    )
  }//end-render
}

这是 Foo class:

import React from 'react'

export default class Foo extends React.Component {
  render() {
    return  <tr>
              <td>{foo.name}</td>
              <td>{foo.surname}</td>
            </tr>
  }
}

这是主渲染:

render(){
    if (this.state.foos.length > 0) {
      console.log('Foos size ' + this.state.foos.length);
      return  <table>
                <tbody>
                  <FooTable foos={this.state.foos}/>
                </tbody>
              </table>
   } else {
     return <p className="text-center">Loading Foos...</p>
   }
}

Webpack 在 FooTable 中标记错误(意外标记)。它由评论标记。

您需要 return 组件(在本例中为 FooTable)渲染方法中的单个节点。

render() {
    return(
    <tr>
      <td>id</td>
      <td>name</td>
      <td>surname</td>
    </tr>
    { //<-- This breaks the single root
      this.props.Foos.map( foo=>{
             return  < Foo key={foo.id} name={foo.name} surname={foo.surname}/>
      })
    }
    )
  }

你需要这样做:

render() {
    return (
      <tbody>
        <tr>
          <td>id</td>
          <td>name</td>
          <td>surname</td>
        </tr>
        {this.props.Foos.map(foo => (<Foo key={foo.id} name={foo.name} surname={foo.surname}/>))}
    </tbody>)
  }

文档说(参见 here):

Note:

One limitation: React components can only render a single root node. If you want to return multiple nodes they must be wrapped in a single root.

您需要将 <tr><Foo> 元素包装在单个节点中,例如 <div>:

render() {
  return(
    <div>
      <tr>
       <td>id</td>
       <td>name</td>
       <td>surname</td>
      </tr>
      { //<-- No more multiple roots
        this.props.Foos.map( foo => {
          return  < Foo key={foo.id} name={foo.name} surname={foo.surname}/>
      }
    </div>
  )
}

希望这对您有所帮助