【问题标题】:ReactJS Cannot read property 'map' of undefinedReactJS无法读取未定义的属性“地图”
【发布时间】:2020-09-14 11:33:38
【问题描述】:

我从搜索中阅读了几篇热门帖子,但到目前为止没有任何内容非常适合我的情况。甚至 VSCode 也能识别该函数,但不知何故 React 不能?

我的 jsx:(编辑:感谢@Dannis Vash,似乎是我最初没有在此处包含的排序算法破坏了代码)

import React, {useState, useEffect} from 'react';
import glossaryItems from '../../data/glossary-items.json';

function Glossary(){

    const [items, setItems] = useState(glossaryItems);

    /* Algorithm that's suspected of breaking the code */
    const sortItems = () =>{
        let sortedItems = [...items.glossaryItems].sort((item1, item2) => {
            if(item1.itemName < item2.itemName){
                return -1;
            }
            if(item1.itemName > item2.itemName){
                return 1;
            }
            return 0;
        });

        setItems(sortedItems);
    }

    /* Sorts the items on component render */
    useEffect(()=>{sortItems()},[]);

    const sortedItems = items;
    console.log(sortedItems); // This does log the entire array
    const glossary = sortedItems.glossaryItems.map((item) =>{
        return(
            {item.name}
        );
    });

    return(
        <div>
            <div className="glossary-body">
                {glossary}
            </div>
        </div>
    );
}

export default Glossary;

我的 json:

{
    "glossaryItems":[
        {
            "itemName": "Item 1",
            "to": "www.google.com"
        },
        {
            "itemName": "Item 2",
            "to": "github.com"
        },
        {
            "itemName": "Item 3",
            "to": "127.0.0.1"
        }
    ]
}

它告诉我它无法读取未定义类型的地图,这对我来说似乎很奇怪,因为当我在 VSCode 中将鼠标悬停在地图上时,它实际上显示了正确的功能。有什么见解吗?谢谢

【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    您的项目密钥是itemName 而不是name

    // not item.name
    const glossary = items.glossaryItems.map(item => item.itemName);
    

    另外,在sortItems 中,您实际上删除了glossaryItems 键:

    // Is an array of objects
    const sortItems = [...items.glossaryItems];
    
    // While you need is an object: { glossaryItems: [...] }
    

    因此你需要将其添加回来或不使用它:

    setItems({ glossaryItems: sortedItems });
    const glossary = items.glossaryItems?.map(item => item.itemName);
    
    // Optionioal chaining.
    setItems(sortedItems);
    const glossary = items?.map(item => item.itemName);
    

    【讨论】:

    猜你喜欢
    • 2017-07-30
    • 2021-11-17
    • 2018-02-08
    • 2020-04-20
    • 2020-11-18
    • 2021-07-11
    • 1970-01-01
    • 2018-09-07
    • 2020-07-06
    相关资源
    最近更新 更多