[英]TypeError: Cannot read property 'map' of undefined, in react hooks crud application
[英]Cannot read property 'map' of undefined with react hooks
我正在尝试使用 fortnite api 来显示当前的商品商店,但我收到了标题中的错误,当我控制台日志结果显示一个数组但我无法通过它映射? 为什么?
import React, { useState, useEffect } from 'react'
import axios from 'axios';
export default function itemShop() {
const [shop, setShop] = useState('')
const API = 'https://fortnite-public-api.theapinetwork.com/prod09/store/get?language={en}'
useEffect(() => {
const fetchData = async () => {
const result = await axios(
API,
);
setShop(result.data);
};
fetchData();
}, []);
const { items } = shop;
console.log(items)
return (
<div>
<p>{shop.date}</p>
{items.map(item => <p>{item.name}</p>)}
</div>
)
}
您需要在渲染之前检查项目是否为空/未定义:
{items && items.map(item => (
<p>{item.name}</p>
))}
问题出在这一行:
const [shop, setShop] = useState('')
由于您希望shop.items
作为数组,因此将初始状态定义为:
const [shop, setShop] = useState({ items: [] });
还为每个p
分配唯一键,这里:
<p key={item.itemid}>{item.name}</p>
你也可以这样做
{ items?.map(item => (<p>{ item.name }</p>)) }
对我来说,我忘记在调用async方法后在axios 中添加await 。 像下面的代码。 如果上述方法对您没有帮助,请务必再次检查您的代码。
async function getCategories() {
try {
const response = axios.get("API");
setCategories(response.data);
} catch (error) {
console.log("error", error);
}
}
如果有人想了解这个问题及其解决方案可以访问网站网站,这对我真的很有帮助https://www.debuggr.io/react-map-of-undefined/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.