TypeError: data.map is not a function in react

huangapple go评论62阅读模式
英文:

TypeError: data.map is not a function in react

问题

我尝试在React中映射数据,代码部分如下:

import React from 'react'
import axios from 'axios'
import { useEffect, useState } from 'react'

export default function Home() {
  const [data, setData] = useState([])
  useEffect(() => {
    axios.get('http://127.0.0.1:8000/api/books').then(res => {
      console.log(res.data)
      setData(res.data)
    }).catch(err => console.log(err))
  }, [])

  return (
    <div>
      {data.map(book => (
        <h1>{book.title}</h1>
      ))}
    </div>
  )
}

在控制台中,数据显示如下:

{data: Array(100)}
data: 
(100) [{}, {}, {}, {}, {}, ]
[[Prototype]]
: 
Object

这个错误是什么问题的解决方法,我尝试了很多方法,但都没有成功,请帮助我解决这个问题。

英文:

I try to map data in react like

import React from &#39;react&#39;
import axios from &#39;axios&#39;
import {useEffect, useState} from &#39;react&#39;

export default function Home() {
  const [data, setData] = useState([])
  useEffect(() =&gt; {
    axios.get(&#39;http://127.0.0.1:8000/api/books&#39;).then(res =&gt; {
      console.log(res.data)
            setData(res.data)
        }).catch(err =&gt; console.log(err))
    }, [])
  
  return (
    &lt;div&gt;
    
    {data.map(book =&gt; (
                &lt;h1&gt;{book.title}&lt;/h1&gt;
            ))}
    &lt;/div&gt;
  )
}

in console data show like

{data: Array(100)}
data
: 
(100) [{…}, {…}, {…}, {…}, {…}, ]
[[Prototype]]
: 
Object

the error is TypeError: data.map is not a function in react how to solve this issue i try many ways but not working please help me

答案1

得分: 3

console.log(res.data) 显示它具有包含数组的数据对象。因此,您应该设置像 setData(res.data.data) 这样的方式。目前,您正在设置对象,无法与 map 一起使用。

英文:

console.log(res.data) shows it has a data object which consists the array. So you should set like setData(res.data.data). Currently you are setting the object, which cannot be used with map

答案2

得分: 1

你可以看到控制台中的数据是 {data: Array(100)}

所以你需要更新状态如下:

  setData(res.data.data)
英文:

You can see the console the data is {data: Array(100)}

so you need to update the state like

  setData(res.data.data)

huangapple
  • 本文由 发表于 2023年2月8日 14:27:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定