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

React+Firestore推特克隆项目评论表单总是提交相同docId如何解决

问题根因

  1. HTML规范要求DOM的id属性全局唯一,但你所有Howl组件里的评论、点赞checkbox的id都是固定值comment-button、like-button,label的htmlFor属性点击时只会匹配页面上第一个出现的对应id的元素,所以不管你点击哪个帖子的评论图标,实际触发的都是最顶部帖子的评论开关,提交的自然也是顶部帖子的表单。
  2. 虽然你给评论表单设置了id为docId,但完全没必要通过事件对象拿id,组件props本身就传入了当前实例的docId,直接用更可靠,也能避免id重复带来的取值错误。

修改方案

1. 把固定id替换为带docId的唯一id

修改Howl组件返回的JSX里的按钮表单部分:

<form action="" className="buttons">
  <label htmlFor={`comment-button-${docId}`}>
    <FontAwesomeIcon icon={faComment} className="image-icon" />
  </label>
  <input
    id={`comment-button-${docId}`}
    type="checkbox"
    onClick={handleComment}
    style={{ display: "none" }}
  />
  <label htmlFor={`like-button-${docId}`}>
    <FontAwesomeIcon icon={faStar} className="image-icon" />
  </label>
  <input
    id={`like-button-${docId}`}
    type="checkbox"
    onClick={handleLike}
    style={{ display: "none" }}
  />
  <label htmlFor={`like-button-${docId}`}>{likes > 0 && likes}</label>
</form>

2. 修改submitComment函数直接使用props传入的docId

不用再从event.target拿id,直接用组件props里的docId即可:

const submitComment = (event) => {
  event.preventDefault();

  const resetComment = () => {
    toggleCommenting(!commenting);
    setNewComment("");
  };

  if (comments) {
    firestore
      .collection("howls")
      .doc(docId)
      .update({
        comments: [...comments, newComment],
      })
      .then(() => resetComment());
  } else {
    firestore
      .collection("howls")
      .doc(docId)
      .update({ comments: [newComment] })
      .then(() => resetComment());
  }
};

修改完成后每个帖子的开关、提交都会对应到自身的docId,不会再错写到顶部帖子里。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:15:02