Firebase 响应太慢 [英] Firebase response is too slow
问题描述
大家好,我正在使用 Firebase 实时数据库为我的 React.js Web 应用获取一些数据.
Hey Guys I'm using Firebase Realtime Database to fetch some data for my React.js Web App.
有一个名为 Corr_User
的 useState
应该存储正确用户名的值.
There is a useState
called Corr_User
that should store the value of correct username.
我有一个 function
可以从 Firebase 获取用户名:-
I have a function
to fetch the username from Firebase : -
function Login(){
const path = firebase.database().ref("users").child(username);
path.once("value")
.then(snapShot => {
setCorr_User(snapShot.child("username").val());
})
当我执行此操作时 console.log(Corr_User)
它打印一个空字符串,指示 useState
未更新.为了确认,我还记录了 snapshot.val()
.这打印了适当的值.
When I do this console.log(Corr_User)
it prints a empty string indicating that the useState
is not updated.
For confirmation, I also logged the snapshot.val()
. This printed the appropriate value.
由此我可以理解 Firebase 返回响应的速度太慢,因此我的 useState
没有得到更新.我的理解正确吗?有没有办法让我的 Login()
函数等待响应?
I could understand from this that Firebase is too slow in returning response hence my useState
is not getting updated. Is my understanding correct? Is there any way to make my Login()
function wait for the response?
请帮忙!!提前致谢.
编辑 -好吧,我猜有点混乱.代码是这样的
EDIT - Ok there was a bit of confusion I guess. The code goes likes this
function Login(){
....
.once("value")
.then(snapShot => { // After fetching the data
setCorr_User(snapShot.child("username").val()); // Assigning the value
console.log(snapShot.val()); // This should be logged first
}) // End of function snapShot()
// This is still inside Login()
console.log(Corr_User) // But this is logged first
} // End of Login()
正是从这里,我猜到 Firebase 的响应速度太慢,并且 useState
没有得到相应的更新,因为 snapShot.val()
仍然是空的.
It is from this, I was able to guess that Firebase is too slow in responding and useState
is not getting updated accordingly as snapShot.val()
is still empty.
推荐答案
数据从 Firebase 异步加载,当数据可用时调用 then
.这实际上意味着您的 console.log(Corr_User)
在 console.log(snapShot.val())
之前被调用.因此,任何需要数据库数据的代码都必须在 then
回调中,或者从那里调用.
Data is loaded from Firebase asynchronously, and the then
is called when that data is available. What this means in practice is that your console.log(Corr_User)
is called before console.log(snapShot.val())
. For this reason, any code that needs data from the database must be inside the then
callback, or be called from there.
对于不熟悉异步 API 的开发人员来说,这是一个非常常见的绊脚石,因此我建议研究其中的一些链接:
This is an incredibly common stumbling block for developers new to asynchronous APIs, so I recommend studying some of these links:
这篇关于Firebase 响应太慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!