[英]Array.map index is undefined?
我的 React 中有以下代码:
{
comments.map((comment, index) =>
console.log({index}),
<Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
)
}
但是,这会返回错误,即在 console.log 行上'index' is not defined no-undef
。 这是 state:
const [comments,setComments] = useState([[]])
为什么会这样?
您需要从 map function 返回一个元素。 在这里你只是尝试一下究竟是什么? 我认为你只需要用{ }
包装你的 function 并使用return
语句。
{
comments.map((comment, index) => {
console.log({index});
return <Textfield key = {index} placeholder ="Add Comment" Id="addComment" />;
})
}
也许您只是在 map function 周围缺少一些花括号
{
comments.map((comment, index) => {
console.log(index);
return <Textfield key={index} placeholder="Add Comment" Id="addComment" />;
})
}
您需要在数组 function 中添加 { }
{
comments.map((comment, index) => {
console.log(index),
return <Textfield key = {index} placeholder = "Add Comment" Id = "addComment" / >
)}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.