【问题标题】:Why does adding/removing curly braces in this arrow function cause the text to not display for a ReactJS component?为什么在这个箭头函数中添加/删除花括号会导致文本不显示 ReactJS 组件?
【发布时间】:2022-01-06 19:45:51
【问题描述】:
    const tasks = [
    {
        id: 1,
        text: 'Doctors Appointment',
        day: "Feb 5th at 2:30 pm",
        reminder: true,
    },
    {
        id: 2,
        text: "Meeting at School",
        day: "Feb 6th at 1:30pm",
        reminder: true,
    },
    {
        id: 3,
        text: "Food Shopping",
        day: "Feb 5th at 2:30pm",
        reminder: false,
    },
];

    const Tasks = () => {
    return (
        <>
            {
                
                    tasks.map((task) =>
                        <h3>{task.text}</h3>
                )
            }
        </>
    )
}

export default Tasks;

这是我的组件。 最初我在箭头函数中有花括号,所以它看起来像这样:

tasks.map((task) => {
                        <h3>{task.text}</h3>
                    }

但是,这样做会使文本消失。于是我去掉了这些花括号,突然出现了文字。

为什么添加花括号会破坏这个箭头函数?

谢谢!

【问题讨论】:

  • map函数中需要返回数据。您编写了一个不带括号的箭头函数,从而隐式返回数据(ES6)

标签: javascript reactjs web


【解决方案1】:

如果您在箭头函数中使用花括号,则需要 return 关键字。

tasks.map((task) => {
                       return <h3>{task.text}</h3>
                    }
)

【讨论】:

    【解决方案2】:

    花括号用于分隔函数体,因此您需要一个return 语句来返回一个值:

    tasks.map((task) => {
      return <h3>{task.text}</h3>
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 2017-08-03
      • 2020-06-18
      • 1970-01-01
      • 2022-01-19
      • 2017-05-22
      • 2019-06-18
      相关资源
      最近更新 更多