import { getDocs, collection, query, doc, addDoc } from "firebase/firestore/lite"; import { useState } from "react"; import { db } from "../firebaseConfig"; import { useEffect } from "react"; function EndGame(startGame){ const {startGameHandler} = startGame; const startGameClick = startGameHandler[0]; const time = startGameHandler[1]; const [leaderboard, setLeaderboard] = useState([]); const [user, setUser] = useState(""); const [username, setUsername] = useState("") const [isAnonymous, setIsAnonymous] = useState(false); const loginAnonymously = () =>{ console.log("login hivas ", user) setUser(username) setIsAnonymous(true) } const setScore= async(timeprop, userprop)=>{ console.log(time, user) await addDoc(doc(db, "Leaderboard"), { name: userprop, time: timeprop, }) } async function getLeaderboard(){ const q = query(collection(db, "Leaderboard")); const chacSnapShot = await getDocs(q); const char = chacSnapShot.docs.map(doc => doc.data()); setLeaderboard(char) } useEffect(()=>{ setScore(time, user) getLeaderboard() }, [isAnonymous]) return( <div className={`endgame-page`}> {!isAnonymous && ( <div className="endgame-div"> <input type="text" placeholder="Enter a username" value={username} onChange={e => setUsername(e.target.value)} /> <button onClick={loginAnonymously}>Login Anonymously</button> </div> )} {isAnonymous && ( <div className="endgame-div"> <h1 className="endgame-heading">Leaderboard</h1> <div className="endgame-leaderboard"> {leaderboard.map((data)=>{ return( <div key={data.name} className="user-container"> <p className="username">{data.name}</p> <p className="userdata">{data.time}</p> </div> ) })} </div> <button className="endgame-button" onClick={startGameClick} >Start Game</button> </div> )} </div> ) } export default EndGame
所以我有这个endgame组件,当它渲染时,由于某些原因,setScore函数被调用,我认为这就是我得到以下错误的原因:
未捕获(承诺中)FirebaseError:无效的文档引用。文档引用必须有偶数个段,但排行榜有 1 个。
在第27行。我是不是错了,认为是因为setScore在渲染时被调用?如果不是,问题/解决方案是什么?
在firebase中,我有一个Leaderboard集合,我希望从用户的时间和姓名创建文档(每个用户应该有1个文档)
P粉6857572392023-09-11 00:12:38
方法 addDoc
应该使用集合引用而不是文档引用。只有在想要指定文档名称时才会使用文档引用,此时应使用 setDoc
,请参考下面的示例代码:
const setScore= async(timeprop, userprop)=>{ console.log(time, user) await setDoc(doc(db, "Leaderboard", "<document-name>"), { name: userprop, time: timeprop, }) }
要更正此问题,请查看下面的示例代码:
const setScore= async(timeprop, userprop)=>{ console.log(time, user) await addDoc(collection(db, "Leaderboard"), { name: userprop, time: timeprop, }) }
您可以查看此文档获取更多信息。