Reactjs 从帖子中删除评论:评论赢了';t删除或错误的注释已删除,注释ID未定义
我正在尝试允许用户从帖子中删除评论。我当前拥有的代码没有返回任何已删除的帖子:{n:0,ok:1,deletedCount:0}。如果我在comments.js中将Reactjs 从帖子中删除评论:评论赢了';t删除或错误的注释已删除,注释ID未定义,reactjs,express,mongoose,put,populate,Reactjs,Express,Mongoose,Put,Populate,我正在尝试允许用户从帖子中删除评论。我当前拥有的代码没有返回任何已删除的帖子:{n:0,ok:1,deletedCount:0}。如果我在comments.js中将\u id更改为id,它将删除一条注释,但始终只删除最早(第一条)的注释。commentId在后端显示为未定义 以下是我的模型: // Comment Model user: { type: Schema.Types.ObjectId, ref: "U
\u id
更改为id
,它将删除一条注释,但始终只删除最早(第一条)的注释。commentId在后端显示为未定义
以下是我的模型:
// Comment Model
user:
{
type: Schema.Types.ObjectId,
ref: "User"
},
comment: {type: String, required: true}
}
// Post Model
{
description: String,
user:
{
type: Schema.Types.ObjectId,
ref: "User"
},
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}]
}
注释和删除按钮的前端映射:
const commentList = (
<>
{props.post.comments && props.post.comments
.map(comment => {
let deleteComment = commentId => {
axios
.put(`/api/comments/${props.postId}`, {commmentId: commentId})
.then(() => {
console.log('-------deleted: ', commentId, '------------------')
props.getSinglePost()
props.getAllPosts()
})
}
return (
<div key={comment._id}>
<p>{comment.comment}</p>
{comment.user.username === props.user.username? <button onClick={()=> deleteComment(comment._id)}>delete comment</button> : <p>{comment.user.username}</p>}
</div>
);
})}
</>
)
它似乎与您的问题没有直接关系,但在返回JSX的映射内创建
deleteComent
函数效率极低。它为数组中的每个元素创建一个新函数。将其移到组件体外部。问题似乎是输入错误。“commmentId”在put正文中有一个额外的“m”。这肯定是导致问题的打字错误。我还将函数移到了地图之外。非常感谢您对我的帮助,React是新的,我花了一周的时间寻找我的错误,认为这是在逻辑上:)现在一切都比以往任何时候都好!
router.put('/:id', (req, res, next) => {
const commentId = req.body.commentId;
console.log("commmentId", commentId) // undefined
Post.findByIdAndUpdate(req.params.id, { $pull: {comments: commentId}})
.then(commentedPost => {
res.json(commentedPost);
return Comment.deleteOne({ _id: commentId}) /// id ???
.then(data => {
console.log("Deleted in comments.js ROUTE: ", data)
})
.catch(err => {
next(err)
})
})
.catch(err => {
res.json(err)
})
})