React中提交评论后重新生成UUIDv4避免Firestore数据覆盖
解决React+Firestore提交评论时UUID重复覆盖的问题
你的代码中useState(uuidv4())仅在组件首次渲染时生成一次UUID,后续多次提交评论都会复用同一个ID,导致Firestore中后提交的评论直接覆盖之前的内容。以下是两种可行的解决方式:
方案一:提交成功后更新UUID状态
利用Firestore set 方法的异步特性,在提交成功的回调里调用setID生成新的UUID:
const [id, setID] = useState(uuidv4()); const [comment, setComment] = useState(""); const handleSubmit = () => { db.collection("Videos") .doc(video.id) .collection("comments") .doc(id) .set({ timestamp: firebase.firestore.FieldValue.serverTimestamp(), comment: comment, id: id, channelName: currentUser.displayName, email: currentUser.email, }) .then(() => { // 提交成功后生成新UUID setID(uuidv4()); // 清空输入框提升用户体验 setComment(""); }) .catch((error) => { console.error("提交评论失败:", error); }); };
方案二:每次提交时临时生成UUID(推荐)
不需要把UUID存在状态里,每次提交评论时直接生成新的UUID,从根源避免重复ID问题,代码更简洁:
const [comment, setComment] = useState(""); const handleSubmit = () => { const newCommentId = uuidv4(); db.collection("Videos") .doc(video.id) .collection("comments") .doc(newCommentId) .set({ timestamp: firebase.firestore.FieldValue.serverTimestamp(), comment: comment, id: newCommentId, channelName: currentUser.displayName, email: currentUser.email, }) .then(() => { setComment(""); }) .catch((error) => { console.error("提交评论失败:", error); }); };
内容的提问来源于stack exchange,提问作者PiWizard3852
相关产品推荐
相关产品推荐

