如何从 API 打印对象列表?.map 不读取数据 [英] How can i print a list of objects from API? .map don't reading the data

查看:28
本文介绍了如何从 API 打印对象列表?.map 不读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 .map 打印页面中的所有公司时,出现以下问题(TypeError cias.map 不是函数):

when i use the .map to print all companies in my page gives the following issue (TypeError cias.map is not a function):

错误

代码:

import fetch from 'isomorphic-unfetch'
import Link from 'next/link'
import { Container } from '../../../styles/pages/container'
import React from 'react'
import { GetStaticProps } from 'next'
import { Cias } from '../../../../model/cias'

export interface CiasProps {
  cias: Cias[]
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export default function CiasBrazil({ cias }: CiasProps) {
  return (
    <Container>
      {console.log(cias)}
      <ul>
        {cias.map(cia => {
          ;<li className="cia" key={cia.Code}>
            <Link
              href="/companies/brazil/[id]"
              as={`/companies/brazil/${cia.Code}`}
            >
              <a>
                <span>{cia.Name}</span>
              </a>
            </Link>
          </li>
        })}
      </ul>
    </Container>
  )
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res = await fetch('http://localhost:3000/api/infocadcias')
  const cias = await res.json()
  return { props: { cias } }
}

CIA 接口:

export interface Cias {
  Code: number
  Name: string
}

API:

API

推荐答案

你的数据就像

{cias: []}

所以要访问 cias,

So to access cias,

  const data = await res.json();
  const cias = data.cias;
  // ....

这篇关于如何从 API 打印对象列表?.map 不读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆