Firestore提交表单后重定向至新创建文档页面失败排查
问题:Firestore文档创建成功后无法正确重定向至对应页面
我在成功创建Firestore文档后,希望重定向到该新文档对应的页面,但我的实现代码无法正常工作,请问哪里出错了?
我的代码:
db.collection("problems").add({ statement: statement, details: { difficulty: difficulty, type: type, title: title }, tags: tags, timestamp: { created: firebase.firestore.Timestamp.now(), modified: firebase.firestore.Timestamp.now() } }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); var problemID; docRef.get() .then( (doc) => { if(doc.exists) { console.log(doc.data()); console.log(doc.id); problemID = doc.id; window.location.replace("/practice/problemID"); } }) })
错误分析
你的代码存在两个核心问题导致重定向失效:
URL变量未正确插值
你写的window.location.replace("/practice/problemID")中,problemID是字符串字面量,而非你定义的变量。浏览器会直接跳转至包含problemID文本的URL,不会替换为实际的文档ID。冗余的
docRef.get()调用
当add()方法成功返回docRef时,docRef.id已经直接包含了新创建文档的ID,完全不需要额外调用get()方法获取文档来拿到ID。这一步不仅多余,还会增加不必要的异步等待。
修正后的代码
简化代码并修复URL拼接问题即可解决:
db.collection("problems").add({ statement: statement, details: { difficulty: difficulty, type: type, title: title }, tags: tags, timestamp: { created: firebase.firestore.Timestamp.now(), modified: firebase.firestore.Timestamp.now() } }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); // 使用模板字符串正确插入文档ID到URL中 window.location.replace(`/practice/${docRef.id}`); }) .catch(function(error) { // 添加错误处理,便于排查文档创建失败的情况 console.error("Error adding document: ", error); });
额外提示
- 采用模板字符串(反引号包裹,
${变量}格式)是JavaScript中拼接变量与字符串的常用且不易出错的方式。 - 新增
catch()块可以捕获文档创建过程中可能出现的错误(如权限不足、网络异常等),帮助你快速定位问题。 - 移除冗余的
docRef.get()调用后,代码更简洁高效,避免了不必要的数据库请求。
内容的提问来源于stack exchange,提问作者Sachin Kumar
相关产品推荐
相关产品推荐

