React+Firestore推特克隆项目评论表单总是提交相同docId如何解决
问题根因
- HTML规范要求DOM的id属性全局唯一,但你所有Howl组件里的评论、点赞checkbox的id都是固定值
comment-button、like-button,label的htmlFor属性点击时只会匹配页面上第一个出现的对应id的元素,所以不管你点击哪个帖子的评论图标,实际触发的都是最顶部帖子的评论开关,提交的自然也是顶部帖子的表单。 - 虽然你给评论表单设置了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
相关产品推荐
相关产品推荐

