英文:
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 '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>
)
}
in console data show like
{data: Array(100)}
data
:
(100) [{…}, {…}, {…}, {…}, {…}, ]
[[Prototype]]
:
Object
the error is 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论