网站搜索

javascript - 在 Next.js 中获取 "Error: data.map is not a function" 错误


我就是不明白,所以这个 fetch 按预期工作:

async function getData() {
  const res = await fetch('https://jsonplaceholder.typicode.com/todos')
  return res.json()
}

export default async function Home() {
  const data = await getData()

  return (
    <div>
      <div className="grid gap-3 grid-cols-fluid">
        {data.map((item: any) => (
          <p key={''}>{item.title}</p>
        ))}
      </div>
    </div>
  )
}

但另一方面,这个例子不起作用:

async function getData() {
  const res = await fetch('https://data.sec.gov/api/xbrl/frames/us-gaap/AssetsCurrent/USD/CY2021Q4I.json')
  return res.json()
}

export default async function Home() {
  const data = await getData()

  return (
    <div>
      <div className="grid gap-3 grid-cols-fluid">
        {data.map((item: any) => (
          <p key={''}>{item.label}</p>
        ))}
      </div>
    </div>
  )
}

它总是显示:

错误:data.map 不是一个函数

我这里漏掉了什么吗?

答案#1

通过使用 data.map(),你是在假设从 API 得到的结果是一个数组。对于第一个情况,这是正确的,因为数据看起来像这样:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  // ...
]

但是第二个回应看起来像这样:

{
  //...
  label: "Assets, Current",
  // ...
  data: [
    {
      accn: "0001104659-21-152249",
      cik: 1750,
      entityName: "AAR CORP",
      loc: "US-IL",
      end: "2021-11-30",
      val: 946700000,
    },
    // ...
  ],
};

这是一个包含 data 数组的对象,如上所示。所以你想要循环遍历它,可以这样使用:

async function getData() {
  const res = await fetch(
    "https://data.sec.gov/api/xbrl/frames/us-gaap/AssetsCurrent/USD/CY2021Q4I.json"
  );
  return res.json();
}

export default async function Home() {
  // 👇🏽 grab the data array and other values as you would like inside the object
  const { data, ccp } = await getData();

  return (
    <div>
      CCP: {ccp}
      <div className="grid gap-3 grid-cols-fluid">
        {data.map((item: any) => (
          <p key={item.entityName}>{item.entityName}</p>
        ))}
      </div>
    </div>
  );
}