首页 > 解决方案 > 使用 nextjs/react 访问 newsapi 时出现“TypeError:data.map 不是函数”

问题描述

我正在尝试使用 nextjs/react 访问 newsapi,但“TypeError:data.map 不是函数”。

我尝试了以下一些在 stackoverflow 上提供的解决方案,但不适用于我的情况。

这是我的代码:

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Batman TV sources</h1>
    <ul>
      {props.sources.map(source => (
        <li key={source.id}>
          <Link as={`/p/${source.id}`} href={`/post?id=${source.id}`}>
            <a>{source.name}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/sources?q=batman')
  //const res = await fetch('https://randomuser.me/api/?results=10')
  //const res = await fetch ('https://newsapi.org/v2/top-headlines?country=us')
  const data = await res.json()

  //console.log(`source data fetched. Count: ${data.length}`)

  return {
    sources: data.map(entry => entry.source)
  }
}

export default Index

这里的短 api 数据看起来像: {"status":"ok","totalResults":38,"articles":[{"source":{"id":"fox-news","name":"Fox新闻"},"author":"Frank Miles","title":....}]}

我知道这是一个对象,但不是数组,并且 map() 对对象无效。但是如何根据上面的代码解决这个问题?

预期的结果应该是显示新的标题但总是得到“TypeError:data.map is not a function”。我尝试了这里建议的解决方案,但没有奏效。我对此有点陌生。

标签: javascriptjson

解决方案


由于您的数据是由于没有方法而无法在其上Object使用的,因此您正在尝试映射数组内部的属性mapObjectmapsourcearticles

改变这个

data.map(entry => entry.source)

对此

data.articles.map(entry => entry.source)

推荐阅读