Firebase报错:Cannot read properties of undefined (reading 'pieceNum_') 求助
解决Firebase错误:Cannot read properties of undefined (reading 'pieceNum_')
错误详情
错误触发于调用get(child(database, \design-tournament/`))`时,具体报错信息:
Firebase error: Cannot read properties of undefined (reading 'pieceNum_')
错误截图:
可能原因及修复方案
1. 引用创建方式不符合API要求
Firebase Realtime Database的child()方法第一个参数必须是DatabaseReference对象,而非直接传入getDatabase()返回的Database实例。你当前的写法会导致内部调用时找不到预期属性,触发报错。
修复代码:
采用以下两种正确方式之一获取数据:
- 直接用
ref()指定完整路径:
get(ref(database, `design-tournament/`)).then((snapshot) => { // 后续逻辑保持不变 })
- 先创建根引用再调用
child():
const dbRootRef = ref(database); get(child(dbRootRef, `design-tournament/`)).then((snapshot) => { // 后续逻辑保持不变 })
2. 数据库实例初始化不完整
检查firebaseConfig2是否包含databaseURL字段(Realtime Database必填配置),同时验证应用初始化是否成功:
// 确保配置包含databaseURL const firebaseConfig2 = { // 其他配置项 databaseURL: "https://你的项目ID.firebaseio.com" // 替换为实际数据库地址 }; // 捕获初始化可能出现的错误 let app2; try { app2 = initializeApp(firebaseConfig2, "server"); const database = getDatabase(app2); console.log("数据库实例初始化成功"); } catch (err) { console.error("初始化失败:", err); }
3. 数据结构与代码预期不匹配
若上述修复后仍报错,检查design-tournament/节点下的数据结构。pieceNum_相关报错可能是数据解析时某个对象未定义导致,可在获取数据后添加日志验证:
let jsonData = snapshot.val(); console.log("获取到的数据结构:", jsonData); // 确认数据是否符合代码处理逻辑
完整修正后的核心代码示例
import { getDatabase, ref, child, get, push, update, onValue } from "https://www.gstatic.com/firebasejs/10.0.0/firebase-database.js"; // 确保配置信息完整正确 const firebaseConfig2 = { apiKey: "你的API_KEY", authDomain: "你的AUTH_DOMAIN", databaseURL: "你的DATABASE_URL", // 必填项 projectId: "你的PROJECT_ID", storageBucket: "你的STORAGE_BUCKET", messagingSenderId: "你的SENDER_ID", appId: "你的APP_ID" }; const app2 = initializeApp(firebaseConfig2, "server"); const database = getDatabase(app2); function downloa2323d() { console.log("Trying to download") // 修正引用创建逻辑 get(ref(database, `design-tournament/`)).then((snapshot) => { if (snapshot.exists()) { let jsonData = snapshot.val(); console.log("获取到的数据:", jsonData); function download(content, fileName, contentType) { const a = document.createElement("a"); // 注意:对象需转为JSON字符串才能正确生成下载文件 const file = new Blob([JSON.stringify(content)], { type: "application/json" }); a.href = URL.createObjectURL(file); a.download = fileName; a.click(); } function onDownload(){ download(jsonData, "design-tournament-game.json", "text/plain"); } onDownload() } else { console.log("No data available"); } }).catch((error) => { console.error(error); }); } document.getElementById("exportGame").addEventListener('click', downloa2323d )
注:原代码中直接将对象传入Blob会导致下载文件内容为[object Object],需用JSON.stringify()转换为JSON字符串。
内容的提问来源于stack exchange,提问作者Sietse Gorris
相关产品推荐
相关产品推荐

