首页 > 解决方案 > Can someone explain to me why one function works and the other don't?

问题描述

So I am working on learning React, I am doing the Road To React book. In the book he used this code

const List = (props) => (
    props.list.map(item => (
      <div key={item.objectID}>
            <span>
              <a href={item.url}> {item.title} </a>
            </span>
            <span>
              {item.author}
            </span>
            <span>{item.num_comments} </span>
            <span>{item.points} </span>
          </div>
    ))
  )

And I used this code

const List = (props) => {
    return props.list.map(item => {
      <div key={item.objectID}>
            <span>
              <a href={item.url}> {item.title} </a>
            </span>
            <span>
              {item.author}
            </span>
            <span>{item.num_comments} </span>
            <span>{item.points} </span>
          </div>
    })
  }

His worked and mine did not work, I been researching and I do not understand why, if someone can please help me understand why.

标签: javascriptreactjs

解决方案


问题是您将大括号更改(为仅{在此处 大括号,...list.map(item => { 并且在您的 jsx 代码之前没有返回语句。

因此,您可以将代码更改为...list.map(item => (或仅return在 jsx 之前添加语句。

...list.map(item => {
    return <div...

推荐阅读