当Myitems是一个空数组时,它说' myitem.map()不是函数'。如何解决?
当Myitems State中存在项目时,网站还可以。但是,如果没有项目,则网站会中断。
const [myItems, setMyItems] = useState([]);
return (
<div className="container my-5">
<div className="row g-5">
{
myItems?.map(myItem => <MySingleItem key={myItem._id} myItem={myItem} handleItemDelete={handleItemDelete} />)
}
</div>
</div>
);
When items are present in myItems state, the website is ok. but if there is no item, the website breaks.
const [myItems, setMyItems] = useState([]);
return (
<div className="container my-5">
<div className="row g-5">
{
myItems?.map(myItem => <MySingleItem key={myItem._id} myItem={myItem} handleItemDelete={handleItemDelete} />)
}
</div>
</div>
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您的
myitems
实际上是接收到不是数组类型的值。执行
将会给出相同的错误
untuff typeError:myitems.map不是函数
。它告诉您
.map
不是一个函数,因为当时myitems
的数据类型是其他的。在组件代码的其余部分中检查您对
setMyItems
的使用情况,或共享完整代码,因为我相信您会错误地将其设置为非阵列类型。The issue is your
myItems
is actually receiving a value that is not an array type.Doing
will give the same error
Uncaught TypeError: myItems.map is not a function
.It's telling you
.map
is not a function because the data type of the value ofmyItems
at that point in time is something else.Check your usage of
setMyItems
in the rest of your component code or share the full code because I believe you're setting it as a non-array type by mistake.