我使用 onAuthStateChange 观察者成功检查了用户的身份验证状态,并将用户重定向到仪表板页面(react-native 项目)。但是,在仪表板上,我已经想显示一些用户特定的数据,例如注册的程序/统计数据。为此,我需要初始化和填充 currentUser 对象,这需要一些时间(我需要从那里获取 uid 以从数据库中获取一些数据)。因此,我正在寻找某种方法来等待此过程成功完成。我正在尝试在 componentDidMount 中使用 async/await 语法,但返回的结果为 null。(相同的语法在其他屏幕中成功运行,但在第一个屏幕中失败)
async componentDidMount() {
try {
let uid = await firebase.auth().currentUser.uid;
console.log(uid);
} catch(error) {
console.log(error);
}
}
等待使用 async/await 语法加载 currentUser 对象的最佳方法是什么?我相信原因可能是firebase返回null作为第一个结果,然后更正uid作为第二个结果。
现在,对于解决方法,我使用简单的 setInterval 函数,但我不想增加太多的加载时间。
let waitForCurrentUser = setInterval(() => {
if ( firebase.auth().currentUser.uid !== null ) {
clearInterval(waitForCurrentUser);
let uid = firebase.auth().currentUser.uid;
this.setState({uid});
return firebase.auth().currentUser.uid;
} else {
console.log('Wait for it');
}
}, 700);