我正在使用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()调用我添加角色之前,Auth状态可能会更改并导航到应用程序。在AppStack中,Direction Component基于角色,我想定位子组件或父组件,但是可以通过调用
firebase.auth (). CurrentUser.getIdTokenResult ()
.then ((idTokenResult) => {
if (idTokenResult.claims.parent || idTokenResult.claims.child) {
}
idTokenResult.claims.parent和idTokenResult.claims.child给出未定义。
我想让用户承担注册和登录的角色,然后使用Direction.js移至相应的组件。
您知道如何解决此问题吗?
不一定是问题的原因,但是太长了,无法发表评论。
无需重复调用onAuthStateChanged
。您只能调用它一次,它将从那一刻开始监听auth状态的更改。在执行过程中在短时间内调用它肯定会带来问题。
改为在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)
...