javascript - 使用 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”。我尝试了这里建议的解决方案,但没有奏效。我对此有点陌生。
解决方案
由于您的数据是由于没有方法而无法在其上Object
使用的,因此您正在尝试映射数组内部的属性map
Object
map
source
articles
改变这个
data.map(entry => entry.source)
对此
data.articles.map(entry => entry.source)
推荐阅读
- ibm-watson - 连接到 Facebook
- ios - Swift - 在图表视图中显示数据
- c# - 如何在 XAF 上的 DetailView 中从当前 ListView 访问 ListView 对象
- regex - 如何对powershell中文件中的每一行使用正则表达式
- firebase - 添加firebase消息后flutter gradle出错
- mysql - MySQL使用游标循环
- r - 在SAS中使用宏分割数据集的R版本
- csv - 使用 awk 在 csv 文件的标题行中添加前缀
- vba - 每当我打开文档时,VBA 代码就会停止
- sql - SQL 选择 team_id 所在的所有项目(1 和 2 以及 3 和 4 以及 .. 列表中的剩余值)