大家好,我正在使用 Firebase 实时数据库为我的 React.js Web 应用程序获取一些数据。
有一个useState
called Corr_User
应该存储正确用户名的值。
我有一个function
从 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()
。这打印了适当的值。
我可以从中了解到 Firebase 返回响应太慢,因此我的useState
没有得到更新。我的理解正确吗?有什么办法可以让我的Login()
函数等待响应?
请帮忙 !!提前致谢。
EDIT -好吧,我猜有一点混乱。代码是这样的
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()
仍然是空的。
数据从 Firebase 异步加载,并且then
当该数据可用时调用。这在实践中意味着您的console.log(Corr_User)
之前被调用console.log(snapShot.val())
。因此,任何需要数据库数据的代码都必须位于then
回调,或者从那里调用。
对于刚接触异步 API 的开发人员来说,这是一个非常常见的障碍,因此我建议研究以下一些链接:
- 为什么 Firebase 在 once() 函数之外会丢失引用? https://stackoverflow.com/questions/40688268/why-does-firebase-lose-reference-outside-the-once-function/40688890#40688890
- 检索 Firebase 数据并返回它的最佳方法,或者替代方法 https://stackoverflow.com/questions/34905600/best-way-to-retrieve-firebase-data-and-return-it-or-an-alternative-way/34908497#34908497
- Firebase 查询内部函数返回 null https://stackoverflow.com/questions/28381006/firebase-query-inside-function-returns-null/28382922#28382922
- 将父作用域中的变量传递给回调函数 https://stackoverflow.com/questions/26297654/passing-variable-in-parent-scope-to-callback-function/26299662#26299662
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)