reactjs - TypeError:无法读取未定义的属性“地图”(React JS)
问题描述
我正在创建一个递归函数,它应该遍历对象类型 ItemType,所以我遇到了一个错误,这个:
TypeError: Cannot read property 'map' of undefined
这是代码:
import React, { useState } from "react";
type ItemType = {
id: Number;
title: String;
children: Array<Number>;
};
// Each "ItemType" element in the array have a array of children ID's. These refer
// to a ItemType.
// = This has a infinite depth.
const items: ItemType[] = [
{ id: 1, title: "Item 1", children: [2, 3, 4] },
{ id: 2, title: "Item 2", children: [1, 3, 4] },
{ id: 3, title: "Item 3", children: [1, 2, 4] },
{ id: 4, title: "Item 3", children: [1, 2, 3] }
];
function Item({ title, children }: ItemType): JSX.Element {
const [open, toggle] = useState(false);
// Given the children array with IDs, find each Item we refer to
const childElements = children.map(findChild) as ItemType[];
return (
<div>
<h6>
{title} children <button onClick={() => toggle(!open)}>Open</button>
</h6>
<ul>
{/* Loop children and run recursive */}
{open &&
childElements.map((child: ItemType) => (
<li>
<div>Child: {child.title}</div>
<Item {...child} />
</li>
))}
</ul>
</div>
);
}
function App() {
return (
<div>
{/* Start by iterating over all items */}
{items.map(item => (
<Item {...item} />
))}
</div>
);
}
// Function to find a Item by child id.
function findChild(childId: Number): ItemType | undefined {
return items.find(({ id }) => id === childId);
}
export default App;
它的代码尝试遍历对象类型 ItemType 并找到每个 Item 的每个子项,当它找到某个子项时它是真的并且应该显示或者当它没有找到某个子项时是错误的,它的代码创建就像一个项目树和在视图中显示,我做错了什么?
解决方案
是children
包含至少一个存在于items
数组中的 id。如果不是,那么children.map()
可能会返回 undefined ,它将被分配给childElements
. 在这种情况下,childElements.map
会给出错误map of undefined
。因为 childElements 是未定义的并且trying to access map from undefined is not possible
.
推荐阅读
- r - 在for循环内计数nrow的R问题
- python - ruamel.yaml:将注释固定到下一个数据项而不是前一个
- reactjs - 重新选择的createSelector:它是否对嵌套对象进行深度比较?
- pandas - 试图从 nbcsport 获取玩家数据
- c# - 如何在 24 小时内将数据表永久保存在“缓存”中?
- python - 解析从 Latex 到 sympy 的实数集
- python - 如何抑制 Python 中 fnmatch 产生的不必要输出?
- python-3.x - 蟒蛇替换'?没有连续或前面的字符
- rust - 迭代中光标的生命周期
- java - 如何配置 Gradle 应用程序插件以按组过滤压缩的依赖项?