我想知道是否有辦法解決這個問題。所以,我正在使用node.js、Mongodb和react.js構建一個博客應用程式。 我添加了評論功能和回復評論功能。到目前為止,一切運行良好。我面臨的挑戰是,我正在使用Mongodb的populate()方法,它處理的是ref id。評論模型有一個參考回復模型的回復陣列。正如我在postman中測驗的那樣,一切都運行良好。現在的挑戰是在reactjs中實作這一點。我希望能夠洗掉每個回復。我已經在react中實作了更新功能,但洗掉功能需要兩個id。這就是我不知道如何得到的。我的路由路徑在node.js中是這樣的:
router. delete("/posts/:id/comments/:commentId/reply/:replyId", async(req, res)=>{
//我的代碼在這里。
}
如你所見,我有帖子ID、評論ID和回復ID。在postman中復制和粘貼它們并測驗你的邏輯很容易。但是用react.js就有點麻煩了。
我有一個評論組件,我通過map()方法渲染了評論陣列。你知道,每個評論都有一個回復陣列。所以,我也映射了回復。現在,要洗掉任何回復,我需要帖子ID、評論ID和回復ID。由于洗掉按鈕來自回復陣列,我如何獲得評論ID?我只能獲取回復的id,但不能獲取評論的id。請看我的反應代碼設定。
comments是評論的陣列,其中有回復。Replies是一個回復陣列。我必須映射到回復中以顯示每個回復。
return (
<div className="comment">
<h5 className='user-comment'> 用戶評論</h5>
{comments.map((singleComment, index)=>{
// console.log(singleComment)
const {author, commentdescription, _id, createdAt, replies} = singleComment
回傳(
< div className='dressed-comments'key={_id}>/span>
<p className="comment-content">/span> {singleComment. commentdescription}</p> {singleComment.
</div>
)
//replies在這里被回傳
{replies.map((singleReply) =>{
const {_id, author, createdAt, replycomment} = singleReply
回傳(
< div className='comment-div' key={_id} >
<i className={isLoading? "cursor-not-allowed singlePostIcon far fa-trash-alt"。 "singlePostIcon far fa-trash-alt" }
onClick={()=> handleDeleteComment(_id)}。
></i>
<p className=" comment-content"> {replycomment}</p>。
</div>/span>
)
handleDeleteComment(_id)是一個洗掉按鈕,單獨抓取回復陣列的id。但是要洗掉每個回復,我還需要從我在回復陣列之前映射的評論陣列中獲取id。
以下是我在react中的洗掉邏輯:
/handle delete reply commmet
const handleDeleteComment = async (id)=>{
try{
await axios. delete(`/posts/${path}/comments/${id}/reply${id}`。{data: {author: user. _id}})。)
window.location.replace("/"/span>)
}catch(err){
}
我有稱為${path}的帖子id,我有回復id,但具體的評論id我似乎無法得到。請提供任何幫助,謝謝。
uj5u.com熱心網友回復:
- 在你的
handleDeleteComment中,傳遞兩個引數而不是一個,comment_id和reply_id。
/h handle delete reply commmet
const handleDeleteComment = async (comment_id, reply_id)=> {
try{
await axios. delete(`/posts/${path}/comments/${comment_id}/reply/${reply_id}。{data: {author: user. _id}})。)
history.replace("/") // See the next point。
} catch(err){
}
}
- 使用
history.replace("/")而不是window.location.replace("/"),因為前者可以導航到新的頁面,而無需對服務器進行新的HTTP呼叫,而后者則會這樣做。
// import
import { useHistory } from "react-router-dom"
...
function MyComponent(props) {
//創建歷史物件。
const history = useHistory();
//其他組件邏輯。
}
- 在解構
singleComment時,要這樣做 。
const {author, commentdescription, _id: comment_id, createdAt, replies} = singleComment
現在你有comment_id用于comment和_id用于回復。只要呼叫你的handleDelete函式即可
onClick={()=> handleDeleteComment(comment_id, _id)}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324677.html
標籤:
