【发布时间】: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 中将鼠标悬停在地图上时,它实际上显示了正确的功能。有什么见解吗?谢谢
【问题讨论】: