[英].map is not a function when fetching data from API reactjs
I'm using an API to fetch data.我正在使用 API 来获取数据。 When I console.log my data, it shows as an array.
当我 console.log 我的数据时,它显示为一个数组。 But when I try to map over it to get the data to display, it tells me that.map is not a function.
但是当我尝试通过 map 来获取要显示的数据时,它告诉我。 I created a custom useFetch hook and then I'm importing it into a separate component.
我创建了一个自定义 useFetch 挂钩,然后将其导入到单独的组件中。 Here's my code and a screenshot of the console.log:
这是我的代码和 console.log 的屏幕截图:
useFetch.js使用Fetch.js
import { useEffect, useState } from 'react'
function useFetch(url) {
const [data, setData] = useState(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error("Sorry, couldn't fetch data for this resource!")
}
return response.json()
})
.then(responseData => {
setData(responseData)
setIsLoading(false)
setError(null)
})
.catch(error => {
setIsLoading(false)
setError(error.message)
})
}, [url])
return { data, isLoading, error }
}
export default useFetch
List.js List.js
import React from 'react'
import useFetch from './useFetch'
function PrizeList2017() {
const { data } = useFetch('http://api.nobelprize.org/v1/prize.json?year=2017&yearTo=2017')
return (
<div className="prize-list-2017-container">
<h1>2017</h1>
{data.map(prize => (
<div key={prize.id}>
<h2>{prize.category}</h2>
</div>
))}
{console.log(data)}
</div>
)
}
export default PrizeList2017
console.log控制台日志
console.log info image console.log 信息图像
Your help is greatly appreciated!非常感谢您的帮助!
This data is not present yep when you try to do the map so do:是的,当您尝试执行 map 时,此数据不存在,因此请执行以下操作:
{data && data.map(prize => (
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.