[英]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.