【问题标题】:Unexpected token (,) when mapping an array in ReactJS [duplicate]在 ReactJS 中映射数组时出现意外的标记 (,) [重复]
【发布时间】:2018-02-10 16:42:24
【问题描述】:

当我尝试在 React 中映射一个数组时(使用此代码):

const { loading, error, posts } = this.props;
    return(
    {posts.map(onePost => ({
        <p key={onePost.id}>{onePost.title}</p>

    }))}
    );

我收到一个错误:

    ERROR in ./src/client/app/mainGrid.jsx
Module build failed: SyntaxError: C:/[redacted]/react/src/client/app/mainGrid.jsx: Unexpected token, expected , (15:8)

  13 |          return(
  14 |
> 15 |          {posts.map(onePost => ({
     |                ^
  16 |                  <p key={onePost.id}>{onePost.title}</p>
  17 |
  18 |          }))}

 @ ./src/client/app/index.jsx 27:16-41

我不知道为什么会这样,我觉得一切都很好。

【问题讨论】:

  • 我会说最里面的 {} 导致了问题 - 要么将 JSX 元素包装在括号中,即 ( &lt;p...&gt; ) 而不是 ({ &lt;p...&gt; }) 要么返回一个普通对象
  • 你正在返回一个 object,它假设 postsposts: posts 的简写,并且在下一个键之前需要一个逗号。

标签: javascript reactjs


【解决方案1】:

我清理了你的sn-p,你有太多不需要的括号。更详细地说,将您的 return 语句包装在 {} 中是告诉 js 您正在返回一个对象,但您正在尝试返回一个表达式(这反过来又返回一个数组)。为了让 js 评估该表达式,您将其包装到 (),然后正常返回。

即使在 .map 内的箭头函数中添加额外的 {} 时,您也要这样做两次,与之前的解释相同。

const { loading, error, posts } = this.props;

return (
  posts.map(onePost => (
    <p key={onePost.id}>{onePost.title}</p>
  )
);

在这种情况下,您可以更进一步并删除 return 语句中的括号:

const { loading, error, posts } = this.props;

return posts.map(onePost => <p key={onePost.id}>{onePost.title}</p>);

【讨论】:

    猜你喜欢
    • 2016-08-28
    • 2017-05-28
    • 2018-03-14
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2017-12-26
    • 2018-04-07
    相关资源
    最近更新 更多