gpt4 book ai didi

javascript - "TypeError: data.map is not a function"使用 nextjs/react 访问 newsapi

转载 作者:行者123 更新时间:2023-11-30 19:31:30 36 4
gpt4 key购买 nike

我正在尝试使用 nextjs/react 访问 newsapi,但出现“类型错误: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

这里的 SHORTED api 数据如下所示:{"status":"ok","totalResults":38,"articles":[{"source":{"id":"fox-news","name":"Fox News"},"author": “弗兰克·迈尔斯”,“标题”:....}]}

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

预期的结果应该是显示新标题,但总是出现“TypeError:data.map 不是函数”。我尝试了此处建议的解决方案,但没有奏效。我对此有点陌生。

最佳答案

因为你的数据是一个 Object 你不能在它上面使用 map 因为 Object 没有 map 方法,您正在尝试映射 articles 数组中的 source 属性

改变这个

data.map(entry => entry.source)

对此

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

关于javascript - "TypeError: data.map is not a function"使用 nextjs/react 访问 newsapi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56388974/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com