首页 > 解决方案 > 查找数组的第一个元素并将其显示在 map 函数中但有警告 - React

问题描述

我有这样的数据:

    {
      "title": 0,
      "name": 0,
      "score": 0,
      "summary": [
        {
          "id": 1,
          "start": "2019-11-01",
          "end": "2019-11-04"
        },
        {
          "id": 2,
          "start": "2019-11-01",
          "end": "2019-11-04"
        }
      ]
    }

我正在尝试访问摘要的第一个元素,所以我尝试了这个:

    const newDate = new Date(data?.summary.map((d: any, index: number) => {
               if (index === 0) {
                 return (
                 new Date(d.start)
               )
          }
     })),

虽然它正在工作,但我收到警告:

Array.prototype.map() 期望在箭头函数 array-callback-return 的末尾返回一个值

我知道这一定是因为我没有在回调中返回任何内容并且返回在 if 语句中?

标签: javascriptarraysreactjs

解决方案


if (index === 0) {
                 return (
                 new Date(d.start)
               )

如果 index === 0,您只会返回一个值。

我不确定您要实现什么目标:

const newDate = new Date(data?.summary.map((d: any, index: number) => {
           if (index === 0) {
             return (
             new Date(d.start)
           )
      }
 })),

我想:

const newDate = newDate(data?.summary[0]?.start) 

会做的事。


推荐阅读