繁体   English   中英

无法使用反应钩子读取未定义的属性“地图”

[英]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>
    )
}

代码沙箱: https : //codesandbox.io/embed/km10wq4y5

您需要在渲染之前检查项目是否为空/未定义:

{items && items.map(item => (
        <p>{item.name}</p>
      ))}

工作: https : //codesandbox.io/s/24vkqzn6xy

问题出在这一行:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM