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(
{!isAnonymous && (
setUsername(e.target.value)}
/>
)}
{isAnonymous && (
Leaderboard
{leaderboard.map((data)=>{
return(
{data.name}
{data.time}
)
})}
)}
)
}
export default EndGame
所以我有这个endgame组件,当它渲染时,由于某些原因,setScore函数被调用,我认为这就是我得到以下错误的原因:
未捕获(承诺中)FirebaseError:无效的文档引用。文档引用必须有偶数个段,但排行榜有 1 个。
在第27行。我是不是错了,认为是因为setScore在渲染时被调用?如果不是,问题/解决方案是什么?
在firebase中,我有一个Leaderboard集合,我希望从用户的时间和姓名创建文档(每个用户应该有1个文档)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
方法
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, }) }您可以查看此文档获取更多信息。