[英]Getting constant error of - Uncaught TypeError: Cannot read properties of undefined (reading 'map')
This is one of my components in the project named Posts.jsx
which displays all the posts received from a component, but as soon as I render the component the page goes blank showing:这是我在名为
Posts.jsx
的项目中的组件之一,它显示从组件接收到的所有帖子,但是一旦我渲染组件,页面就会变为空白,显示:
Uncaught TypeError: Cannot read properties of undefined (reading 'map').
Even if I write posts?.即使我写帖子? maps... it doesn't work.
地图......它不起作用。 Please help me with this.
请帮我解决一下这个。
import Post from "../post/Post";
import "./posts.css";
export default function Posts({posts}) {
return (
<>
<div className="posts">
{posts.map((p) =>{
{console.log(p)}
<Post post = {p} />
})}
</div>
</>
);
}
Your prop posts
is undefined
.您的道具
posts
undefined
。 Check what value you pass to the component and make sure this is an array.检查您传递给组件的值并确保这是一个数组。
It happens if posts
is fetched by the consumer of the component from an API trough a request for example.例如,如果组件的使用者通过请求从 API 获取
posts
,则会发生这种情况。 While the data is being fetched posts
may be undefined
depending on how you implement it.在获取数据时,
posts
可能undefined
,具体取决于您的实现方式。 A solution is to check with ?
一个解决方案是检查
?
( Optional Chaining Operator ). ( 可选的链接运算符)。 Like so:
像这样:
import Post from "../post/Post";
import "./posts.css";
export default function Posts({posts}) {
return (
<>
<div className="posts">
{posts?.map((p) =>{
{console.log(p)}
<Post post = {p} />
})}
</div>
</>
);
}
If you are still getting the error it means posts
is not an array, make sure it's one when defining it, change it and also when passing it to the component.如果您仍然收到错误,这意味着
posts
不是一个数组,请确保在定义它、更改它以及将它传递给组件时它是一个数组。
The problem is that you imported Post
with a capital P
and you are trying to map post
with a small p
Use this code to correct it问题是您使用大写
P
导入Post
并且您正在尝试post
使用小p
发布使用此代码更正它
import Post from "../post/Post";
import "./posts.css";
export default function Posts({posts}) {
return (
<>
<div className="posts">
{Posts.map((p) =>{
{console.log(p)}
<Post post = {p} />
})}
</div>
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.