【问题标题】:Cannot read property 'map' of undefined with react hooks无法使用反应挂钩读取未定义的属性“地图”
【发布时间】:2019-09-04 03:03:35
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      问题出在这一行:

      const [shop, setShop] = useState('')
      

      由于您期望 shop.items 是一个数组,因此将初始状态定义为:

      const [shop, setShop] = useState({ items: [] });
      

      还为每个p 分配唯一键,这里:

      <p key={item.itemid}>{item.name}</p>
      

      Working Code.

      【讨论】:

        【解决方案3】:

        你也可以这样做

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

        【讨论】:

          【解决方案4】:

          对我来说,在调用 async 方法后,我忘记在 axios 中添加 await。像下面的代码。如果上述方法对您没有帮助,请务必再次检查您的代码。

          async function getCategories() {
                try {
                  const response = axios.get("API");
                  setCategories(response.data);
                } catch (error) {
                  console.log("error", error);
                }
              }
          

          【讨论】:

            【解决方案5】:

            如果有人想了解这个问题并且它的解决方案可以访问该网站,这对我真的很有帮助 https://www.debuggr.io/react-map-of-undefined/

            【讨论】:

              猜你喜欢
              • 2021-04-12
              • 2020-06-30
              • 2021-03-14
              • 2021-12-27
              • 1970-01-01
              • 1970-01-01
              • 2022-01-25
              • 2018-12-18
              • 1970-01-01
              相关资源
              最近更新 更多