情況:對于我使用實時資料庫的應用程式專案,我試圖從與用戶關聯的所有機器加載資料。用戶應該看到的機器取決于相關公司 (cid) 以及哪些機器屬于該公司。
問題:我盡可能多地使用了Firebase v9 檔案,并創建了您可以在下面看到的代碼。但是,此代碼僅在 3 次重新渲染后回傳正確的機器。看起來每個onValue命令只在重新渲染后回傳一些東西。有人可以向我解釋一種無需強制重新渲染螢屏即可獲取完整資料的方法嗎?我已經嘗試get異步使用該命令,但這似乎沒有改變任何東西。
Firebase 布局圖片
useEffect(() => {
const auth = getAuth();
const db = getDatabase();
const userRef = ref(db, "users/" auth.currentUser.uid "/cid");
onValue(userRef, (snapshot) => {
const cid = snapshot.val();
setCid(cid, true);
});
const machinesRef = ref(db, "companies/" cid "/machines");
onValue(machinesRef, (snapshot) => {
const fetchedData = [];
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const parsRef = ref(db, "machines/" childKey);
onValue(parsRef, (snapshot) => {
const parData = snapshot.val();
fetchedData.push(
new Machine(
childKey,
cid,
childData.type,
childData.creation,
parData.temperature
)
);
});
});
setData(fetchedData);
});
console.log(cid); # Outputted in the results section
console.log(data); # Outputted in the results section
}, []);
結果:
渲染 1:
null
Array []
渲染 2:
cid # This is correct
Array []
渲染 3:
cid
Array [
Machine {
"companyId": "cid",
"creation": "creation",
"id": "23rff3345GRR",
"temperature": 99,
"type": "type",
},
Machine {
"companyId": "cid",
"creation": "creation",
"id": "3454egGR3",
"temperature": 2,
"type": "type",
},
]
uj5u.com熱心網友回復:
您需要將呼叫移動setData到onValue處理程式中:
onValue(machinesRef, (snapshot) => {
const fetchedData = [];
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const parsRef = ref(db, "machines/" childKey);
onValue(parsRef, (snapshot) => {
const parData = snapshot.val();
fetchedData.push(
new Machine(
childKey,
cid,
childData.type,
childData.creation,
parData.temperature
)
);
setData(fetchedData); // ??
});
});
如果您將它留在回呼之外,它將在呼叫之前運行fetchedData.push(...)。檢查這一點的最簡單方法是在兩行上設定斷點并在除錯器中運行,或者添加一些日志記錄并檢查輸出順序。
有關此問題的詳細解釋,請參閱:為什么 Firebase 在 once() 函式之外丟失參考?(在 v9 之前,但無論版本如何,行為都完全相同)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/398859.html
標籤:javascript 火力基地 反应原生 火力实时数据库 世博会
