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, }) }
您可以查看此文件以取得更多資訊。