React Native接入Firestore校验emailVerifiedAccount出现异常跳转问题
问题原因
- 异步方法未正确等待结果:
isEmailVerifiedAccount是async异步方法,调用时没有加await关键字,导致checkEmailVerifiedAccount拿到的是Promise对象而非实际的查询结果,严格等于true的判断逻辑失效,同时代码不会等待查询完成就继续执行。 - 文档ID传参错误:
onAuthStateChanged返回的user是Firebase Auth的完整用户实例对象,你直接将该对象传给doc()作为文档ID,无法匹配到Firestore中对应用户ID的文档,导致查询不到数据,返回结果不符合预期。 - 返回值结构不匹配:
isEmailVerifiedAccount方法返回的是{emailVerifiedAccount: 布尔值}的对象,而非直接返回布尔值,直接和true做全等判断永远不成立。 - Alert调用参数错误:React Native的
Alert.alert接收的参数依次为标题、内容、按钮数组,你的代码中第三个参数传入了字符串,会导致Alert初始化异常,可能触发逻辑跳过弹窗直接执行后续代码。
解决方案
1. 修改firestore.js中的isEmailVerifiedAccount方法
isEmailVerifiedAccount = async (userUid) => { try { const snapshot = await firestore() .collection('users') .doc(userUid) .get(); if (snapshot.exists) { const userData = snapshot.data(); // 直接返回布尔值简化上层判断逻辑 return !!userData.emailVerifiedAccount; } return false; } catch (error) { console.log(error); return false; } };
2. 修改登录页的onAuthStateChanged回调
const onAuthStateChanged = async (user) => { if (user) { try { // 等待异步查询完成,传入用户uid作为查询参数 const checkEmailVerifiedAccount = await firestoreService.isEmailVerifiedAccount(user.uid); if(checkEmailVerifiedAccount === true){ navigation.navigate('Index'); }else{ Alert.alert( "Verify as a Playbookx user", "Please click on email verification link send to your email. If you do not receive any email ,please contact user support\nYou may come back to login again after you verified your email", [ { text: "OK"} ] ) } } catch (error) { console.log(error); } } };
内容的提问来源于stack exchange,提问作者Moo Zhen Cong
相关产品推荐
相关产品推荐

