javascript - 如何迭代嵌套在对象中的数组作为道具
问题描述
我有一个我正在解析数据的 JSON 文件,但我正在尝试映射一个子数组(嵌套在一个对象中)。但是,我收到一个错误,说数组不可迭代。我将数组记录到打印数组的控制台,但是当我检查它的类型时,它显示“对象”。
这是我的代码:
export default function Projects({ children, ...props }) {
return (
<div>
<div>
<div className={styles.text}>
<p>{props.description}</p>
<ul>
{props.features.map((feature) => (
<li>{feature}</li>
))}
</ul>
</div>
</div>
</div>
);
}
JSON 文件:
[
{
"id": 1,
"name": "Netflix Clone",
"img": "/netflix-clone.jpg",
"direction": "row",
"description": "This project is a minimalistic Netflix clone utilising Firefox for storage and authorisation. It utilises Styled Components for styling, compound components, large-scale React architecture, and custom hooks.",
"features": [
"React",
"Styled Components",
"Compound components",
"Large-Scale React Architecture",
"Firebase (Firestore & Auth)",
"Functional components",
"Firebase (Firestore & Auth)",
"Custom hooks"
]
},
]
错误:
TypeError: Cannot read property 'map' of undefined
解决方案
在初始渲染时,特征中还没有数据。像这样使用条件 ->
props && props.features && props.features.map((feature) => (
<li>{feature}</li>
))}
推荐阅读
- ethereum - Solidity:事件触发但状态未在委托调用后更新
- angular - 在 Firebase 存储中上传远程图像
- javascript - 从 HTML 正文中抓取 JSON 值
- hibernate - 如何在春季批处理中禁用二级缓存?
- tfs - 当密码中包含双引号时,Team Foundation 版本控制命令失败
- laravel - 雄辩的关系 - whereNotNull 不存在
- authentication - 如何使用 Xamarin.forms 使用 FaceID?
- angularjs - 将条件视图逻辑移动到控制器方法
- excel - Excel公式:根据单元格计算平均值
- html - 如何在不丢失部分图像的情况下将背景图像调整为内容(无背景大小:封面)