[英]How to Fetch Data from Firebase Realtime Database in React Native App
[英]How fetch data from firebase realtime database in react js
我正在嘗試從 React 中的 Firebase 獲取數據。 我的數據結構如下:
我的代碼目前看起來像這樣:
fire.database().ref(outputClassName).once("value", snapshot => {
let classStudents = [];
snapshot.forEach(snapsh => {
//classStudents.push(snapsh.val());
let student = "";
student = snapsh.val();
alert(student);
fire.database().ref(outputClassName).child(student).once("value", snapsho => {
let studentSubjects = [];
snapsho.forEach(snaps => {
//studentSubjects.push(snaps.val());
fire.database().ref(outputClassName).child(student).child(snaps.val()).once("value", snapsh => {
let subjectNotes = [];
snapsh.forEach(snap => {
subjectNotes.push(snap.val());
});
studentSubjects.push(subjectNotes);
});
});
classStudents.push(studentSubjects);
});
});
setRenderData(classStudents);
});
我收到此代碼的錯誤。 有人可以幫我解決問題嗎?
當數據只需要獲取一次時,你應該使用.once()
而不是.on()
。 此外,當您在路徑/10 A
獲取數據時,它將獲取完整的節點,因此您不必再次請求該 class 中每個學生的數據。
function outputData() {
fire.database().ref(outputClassName).once("value").then((snapshot) => {
const classData = snapshot.val()
const students = Object.keys(classData)
students.forEach((student, i) => {
const subjects = Object.keys(classData[student])
console.log(`${i+1} Name: ${student}`)
console.log(`Subjects: ${JSON.stringify(subjects)}`)
console.log("===")
// render the data to HTML as per needs
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.