数据地图功能在 Reactjs 中不起作用
2023-01-28
402
我正在使用 Reactjs 并使用 nextjs 框架,现在我正在尝试使用 map 函数获取数据(url 是 - https://dummyjson.com/products )但我收到以下错误
TypeError: Cannot read property 'length' of undefined
这是我当前的代码
import { useEffect, useState } from "react"
export default function Test() {
const [data, setData] = useState<any>();
useEffect(() => {
const callData = async () => {
const data = await fetch('https://dummyjson.com/products').then(data => data.json())
console.log(data);
setData(data)
}
callData()
}, [])
return(
<div>
{
data.length ? data.map(({}) => <p key={data.id}>{data.title}</p>) : <h3>There are no records yet</h3>
}
</div>)
}
3个回答
-
最初
data
是undefined
,因此使用可选链检查嵌套属性。 -
返回的数据是一个对象;您想要访问
products
字段。 -
将
Array#map
回调的第一个参数命名为您实际上可以访问它。
{data?.products?.length ? data.products.map(product => <p key={product.id}>{product.title}</p>)
: <h3>There are no records yet</h3>}
Unmitigated
2023-01-28
尝试使用空数组初始化
data
状态:
const [data, setData] = useState<any>([]);
您还应该将
data.map(({}) => <p key={data.id}>{data.title}</p>)
更改为
data?.map(({id,title}) => <p key={id}>{title}</p>)
sonEtLumiere
2023-01-28
//Follow this code. your data in the products array so if you want to map then you have to pass array.
import { useEffect, useState } from "react";
export default function Test() {
const [data, setData] = useState<any[]>([]);
useEffect(() => {
const callData = async () => {
const data = await fetch('https://dummyjson.com/products').then(data => data.json())
console.log(data);
setData(data?.products)
}
callData()
}, [])
return(
<div>
{
data.length ? data.map((product) => <p key={product.id}>{product.title}</p>) : <h3>There are no records yet</h3>
}
</div>)
}
Md Wahiduzzaman Emon
2023-01-28