我正在尝试使用 nextjs/react 访问 newsapi,但"TypeError:data.map 不是一个函数"。
我已经尝试了以下一些在堆栈溢出上提供的解决方案,但不适用于我的情况。
这是我的代码:
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
这里 SHORTED API 数据如下所示:{"status":"ok","totalResults":38,"articles":[{"source":{"id":"fox-news","name":"Fox News"},"author":"Frank Miles","title":....}]}
我知道这是一个对象,但不是数组,map(( 对对象无效。但是我如何根据上面的代码解决这个问题呢?
预期的结果应该是显示新的标题,但总是得到"类型错误:data.map 不是一个函数"。我尝试了此处建议的解决方案,但没有奏效。我对此有点陌生。
您的数据是Object
因此您不能对其使用map
,因为Object
没有map
方法,因此您正在尝试映射数组articles
source
属性
更改此内容
data.map(entry => entry.source)
对此
data.articles.map(entry => entry.source)