如何解决每当我尝试访问 record.username 时,我都会收到“TypeError:无法读取未定义的属性‘用户名’”
{record.userId.username}
它说 userId 基本没有 uesrname 即使我在其中引用了一个最初包含“username”的路由“USER”:
制作评论功能:
const makeComment = async (text,postId)=>{
await fetch('/posts/' + post._id + '/comment',{
method:"put",headers:{
"Content-Type":"application/json",},body:JSON.stringify({
postId,text
})
}).then(res=>res.json())
.then(result=>{
console.log(result)
const newData = data.map(item=>{
if(item._id==result._id){
return result
}else{
return item
}
})
setData(newData)
}).catch(err=>{
console.log(err)
})
}
我在 javascript 中添加的部分以在应用程序中显示。这就是问题似乎发生的地方(我通过反复试验发现了)。 {record.userId.username}
它说 userId 基本没有 uesrname 即使我在其中引用了一个最初包含“用户名”的路由“USER”:
{
post.comments.map(record=>{
return(
<h6 key={record._id} className="textInput"><span style={{fontWeight:"500"}}>{record.userId.username}</span> {record.text}</h6>
)
})
}
</div>
<form onSubmit={(e)=>{
e.preventDefault()
makeComment(e.target[0].value,post._id)
}}>
<input type="text" placeholder="add a comment"/>
</form>
解决方法
您需要在显示之前检查您的变量是否有值。 试试这个:
post ? post.comments.map(record=>{
return(
<h6 key={record._id} className="textInput"><span style={{fontWeight:"500"}}>{record.userId.username}</span> {record.text}</h6>
)
}) : <></>
如果您的变量有任何值,它将继续映射。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。