【问题标题】:.map is not a function when fetching data from API reactjs从 API reactjs 获取数据时,.map 不是函数
【发布时间】:2023-03-08 20:24:01
【问题描述】:

我正在使用 API 来获取数据。当我 console.log 我的数据时,它显示为一个数组。但是当我尝试映射它以获取要显示的数据时,它告诉我 .map 不是一个函数。我创建了一个自定义 useFetch 挂钩,然后将其导入到单独的组件中。这是我的代码和 console.log 的屏幕截图:

useFetch.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

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

非常感谢您的帮助!

【问题讨论】:

    标签: javascript arrays reactjs api map-function


    【解决方案1】:

    当您尝试绘制地图时,此数据不存在,所以这样做:

      {data && data.prizes && data.prizes.map(prize => (
    

    【讨论】:

    • 您好!是的,我已经尝试过了,但仍然遇到同样的错误。
    • 我没有看到控制台日志,data实际上是一个对象,data.prizes一个数组
    • 好吧,我想是这样,但 console.log 说的是数组!我仍然不确定如何从对象中提取数据!
    • 尝试用data.prizes映射,应该是,我编辑了我的消息
    • 哦,非常感谢您的成功!救生员!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多