Array.map索引未定义



我的React中有以下代码:

{
comments.map((comment, index) =>
console.log({index}), 
<Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
)
}

但是,这会在console.log行中返回错误'index' is not defined no-undef。这就是状态:

const [comments,setComments] = useState([[]])

为什么会发生这种情况?

您需要从map函数返回一个an元素。给你试一下到底是什么?我认为您只需要用{ }包装您的函数,并使用return语句。

{
comments.map((comment, index) => {
console.log({index});
return <Textfield key = {index} placeholder ="Add Comment" Id="addComment" />;
})
}

也许您只是在映射函数周围缺少了一些大括号

{
comments.map((comment, index) => {
console.log(index);
return <Textfield key={index} placeholder="Add Comment" Id="addComment" />;
})
}

您需要在数组函数中添加{}


{
comments.map((comment, index) => {
console.log(index), 
return <Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
)}
}

最新更新