You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reactjs中如何更新评论数组并同步到Node.js+MongoDB后端

问题原因&修复方案

首先你遇到的404错误由两个低级错误直接导致:

  1. 请求路径拼接错误
    你的后端路由是/posts/:id/comment/:commentId,但你前端拼接的路径是"/posts/"+ path + "/comment" + commentId,comment和commentId之间缺少斜杠,最终请求地址会变成类似/posts/123/comment456,和后端路由不匹配自然报404。
  2. commentId取值错误
    你写的const commentId = comments.map((singleId) => singleId._id ==id)完全是多余的:map方法返回的是布尔值数组,根本不是你要的评论ID。实际上handleCommentUpdate接收的参数id就是你传进来的评论_id,直接用就行。

其他需要修复的连带bug
  • updateComment的初始值不该是布尔值,你现在逻辑是用它存当前正在编辑的评论ID,初始值设为null更合理
  • 点击更新按钮的绑定逻辑错误:你写的onClick={handleCommentUpdate(_id)}会在组件渲染时直接执行函数,应该改成箭头函数onClick={() => handleCommentUpdate(_id)}
  • 进入编辑模式时,textarea没有默认填充原有评论内容,用户点编辑后还要重新输入全部内容,体验很差。建议在点击编辑按钮时,同时把当前评论的内容赋值给commentdescription2
  • 更新成功后没必要强制刷新整页,直接修改本地的comments数组更新视图即可,体验更流畅

修正后的核心代码

状态定义修改

// 初始值改为null,存储正在编辑的评论ID
const [updateComment, setUpdateComment] = useState(null);
const [commentdescription2, setCommentDescription] = useState("");

编辑按钮点击逻辑修改

<i className="singlePostIcon fas fa-edit" 
  onClick={() => {
    setUpdateComment(_id);
    // 点击编辑时填充原有评论内容
    setCommentDescription(singleComment.commentdescription);
  }}  
></i>

更新按钮绑定逻辑修改

<button 
  className='comment-btn'
  onClick={() => handleCommentUpdate(_id)}
>
  更新评论
</button>

handleCommentUpdate函数重写

const handleCommentUpdate = async (commentId) => {
  try {
    // 修正路径拼接
    await axios.put(`/posts/${path}/comment/${commentId}`, {
      author: user._id, 
      commentdescription: commentdescription2,
    });
    // 本地更新评论列表,不需要刷新页面
    setComments(comments.map(comment => 
      comment._id === commentId 
        ? {...comment, commentdescription: commentdescription2} 
        : comment
    ));
    // 退出编辑模式
    setUpdateComment(null);
  } catch(err) {
    console.log(err);
  }
}

内容的提问来源于stack exchange,提问作者kinhs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 13:18:00