javascript - Firebase,用户注册和导航问题
问题描述
我正在使用 React Native、Firebase 和 react-navigator。
在 LoadingScreen 组件中,我观察到状态变化(onAuthStateChanged)
componentDidMount() {
this.timer = setInterval(
() => firebase.auth().onAuthStateChanged(user => {
user ? this.props.navigation.navigate("App") : this.props.navigation.navigate("Auth");
}),
30,
);
}
在 ChooseRole 组件的 AuthStack 中,我有一个函数,我想在其中注册用户以及要执行的角色。
if (this.state.role === 'child') {
Firebase
.auth ()
.createUserWithEmailAndPassword (email, password)
.then (() => {
const addChildRole = fc.httpsCallable (('addChildRole'));
addChildRole ({email: this.state.email}). then ((result) =>
this.setState ({role: result}));
})
.catch (errorMessage => {
console.log (errorMessage)
});
})
问题是在 .then() 调用女巫之前,我添加了一个角色,身份验证状态可能会更改并导航到应用程序。在 AppStack 中,Direction 组件,基于角色,我想定位子组件或父组件,但是通过调用
firebase.auth (). CurrentUser.getIdTokenResult ()
.then ((idTokenResult) => {
if (idTokenResult.claims.parent || idTokenResult.claims.child) {
}
idTokenResult.claims.parent 和 idTokenResult.claims.child 给出未定义的。
我想处理给用户注册和登录的角色,然后使用 Direction.js 移动到适当的组件。
你知道如何解决这个问题吗?
解决方案
不一定是您的问题的原因,但时间太长而无法发表评论。
无需反复调用onAuthStateChanged
。你可以只调用一次,它会从那一刻起监听身份验证状态的变化。当你这样做时,在很短的时间间隔内调用它一定会带来问题。
componentDidMount
改为执行此操作:
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
user ? this.props.navigation.navigate("App") : this.props.navigation.navigate("Auth");
});
}
问题的原因很可能onAuthStateChanged
是在您的数据库写入完成之前触发。您可以通过添加一些日志语句轻松地验证这一点。
如果是,您有两个主要选项来解决此问题:
- 不要在 中使用
onAuthStateChanged
侦听器componentDidMount
,而只需检查 的值firebase.auth().currentUser
。这不使用侦听器,因此不会干扰数据库写入。 在创建用户之前删除
onAuthStateChanged
它,这样它就不会触发。您可以通过保留调用的返回值来做到这一点onAuthStateChanged
,这是一个取消订阅函数。所以类似于:componentDidMount() { stopAuthStateListener = firebase.auth().onAuthStateChanged(user => { ...
接着:
if (this.state.role === 'child') { stopAuthStateListener(); Firebase .auth () .createUserWithEmailAndPassword (email, password) ...
推荐阅读
- android - 对对象的图像属性使用字符串 url 或 URI
- c# - Xamarin iPhone 模拟器不显示实时代码更改
- powershell - 以编程方式更改 Power BI 文件中的数据源
- generative-adversarial-network - 一阶对抗性攻击与其他二阶对抗性攻击有什么区别
- vue.js - Braintree DropIn 数据收集
- c++ - 通过克隆另一个容器的元素来创建智能指针容器
- c# - 在 WPF 中登录时并行运行进度条“不确定”
- vue.js - 如何在 VuePress 中计算数字?
- typescript - 如何使用 Mongoose 6.0.8 连接到在 Docker 中运行的 Mongo Standalone ReplicaSet?
- php - 如何使用 Foreach PHP 从 API 获取数据