[英]I am getting "TypeError: Cannot read property 'username' of undefined" whenever I try to access record.username
{record.userId.username}
it says userId bascially doesnt have uesrname even though I referenced a route "USER" in it which originally contains "username": MAKECOMMENT FUNCTION: {record.userId.username}
它说 userId 基本上没有 uesrname,即使我在其中引用了最初包含“username”的路由“USER”:MAKECOMMENT FUNCTION:
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)
})
}
PORTION WHERE I ADD in javascript for diplay on application.我在 javascript 中添加的部分用于显示应用程序。 This is where the problem seems to occur(I figured out using trial and error).
这就是问题似乎发生的地方(我通过反复试验发现)。
{record.userId.username}
it says userId bascially doesnt have uesrname even though I referenced a route "USER" in it which originally contains "username": {record.userId.username}
它说 userId 基本上没有 uesrname,即使我在其中引用了最初包含“username”的路由“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>
You need to check if your variable has values before displaying it.您需要在显示变量之前检查变量是否具有值。 Try this:
尝试这个:
post ? post.comments.map(record=>{
return(
<h6 key={record._id} className="textInput"><span style={{fontWeight:"500"}}>{record.userId.username}</span> {record.text}</h6>
)
}) : <></>
if your variable has any values, it will continue to map.如果您的变量有任何值,它将继续到 map。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.