React开发博客删除评论回复时如何获取所需的commentId与replyId
解决步骤
1. 修正渲染逻辑的语法错误
你当前的代码中,singleComment 遍历的回调里提前返回了评论节点,导致后续的回复列表遍历逻辑不会被执行,需要将回复列表的遍历放到评论节点的内部。
2. 给删除事件传递多参数
由于回复列表的遍历处于单条评论的作用域内,可以直接拿到当前评论的_id(即你需要的commentId),点击删除时直接将commentId和replyId一同传给处理函数即可。
修正后的渲染代码示例:
return ( <div className="comment"> <h5 className='users-comment'>Users comments</h5> {comments.map((singleComment, index)=>{ // 解构时将评论id重命名为commentId避免和回复id冲突 const {author, commentdescription, _id: commentId, createdAt, replies} = singleComment return ( <div className='displayed-comments' key={commentId}> <p className="comment-content"> {singleComment.commentdescription}</p> {/* 把回复遍历放到评论节点内部,才能拿到外层的commentId */} {replies.map((singleReply) =>{ // 解构时将回复id重命名为replyId const {_id: replyId, author, createdAt, replycomment} = singleReply return( <div className='comment-div' key={replyId} > <i className={isLoading? "cursor-not-allowed singlePostIcon far fa-trash-alt":"singlePostIcon far fa-trash-alt" } // 同时传递commentId和replyId给处理函数 onClick={()=> handleDeleteComment(commentId, replyId)} ></i> <p className="comment-content">{replycomment}</p> </div> ) })} </div> ) })} </div> )
修正后的删除处理函数:
const handleDeleteComment = async (commentId, replyId) =>{ try{ // 修正路径拼写,补充reply前的斜杠,区分两个id参数 await axios.delete(`/posts/${path}/comments/${commentId}/reply/${replyId}`, {data: {author: user._id}}); window.location.replace("/") }catch(err){ console.error(err) } }
内容的提问来源于stack exchange,提问作者kinhs
相关产品推荐
相关产品推荐

