我有一个JSON文件,我正在解析数据,但我试图映射一个子数组(嵌套在对象中)。然而,我得到一个错误,告诉我数组是不可迭代的。我将数组记录到控制台,在那里它打印数组,但当我检查它的类型时,它显示为"object“。
下面是我的代码:
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发布于 2020-10-14 13:17:28
在异步加载数据时,组件的初始渲染将无法访问数据(数据将为undefined)。
您的组件应该通过显示不同的视图来处理这种情况,例如加载动画。
这可以通过在呈现组件之前检查是否定义了props.features来实现:
export default function Projects({ children, ...props }) {
return (
<div>
<div>
<div className={styles.text}>
<p>{props.description}</p>
<ul>
{
/** Conditionally show only when props.features has a truthy value **/
!!props.features && props.features.map((feature) => (
<li>{feature}</li>
))
}
</ul>
</div>
</div>
</div>
);
}要在加载数据时显示另一个组件/文本,您可以使用一个三元语句:
export default function Projects({ children, ...props }) {
return (
<div>
<div>
<div className={styles.text}>
<p>{props.description}</p>
<ul>
{
/** Ternary statement to show components when props.features is a truthy value
or loading when a falsy value **/
props.features ?
props.features.map((feature) => (
<li>{feature}</li>
)) :
"Loading..."
}
</ul>
</div>
</div>
</div>
);
}发布于 2020-10-14 12:58:19
在初始渲染时,要素中还没有数据。像这样的->使用条件
props && props.features && props.features.map((feature) => (
<li>{feature}</li>
))}https://stackoverflow.com/questions/64346753
复制相似问题