我有这样的代码来检查用户是否已经在Firebase中注册了,如果是的话,使用Redux来分派一个操作,并将状态更新到当前的auth用户。
/**
* check to see if the user has signed in already or not
*/
function initAuth(dispatch) {
return new Promise((resolve, reject) => {
const unsubscribe = firebase.auth().onAuthStateChanged(
authUser => {
dispatch({ type: "INIT_AUTH", payload: authUser });
unsubscribe();
resolve();
},
error => reject(error)
);
});
}
initAuth(store.dispatch)
.then(() => render())
.catch(error => console.error(error));
我感到困惑的是,为什么取消订阅()在取消订阅中被调用?我知道你可以像在JavaScript递归中那样做,但是这里有什么用呢?谢谢!
发布于 2017-10-31 19:31:31
onAuthStateChanged
接受一个函数,因为它是唯一的参数。当auth状态发生变化时,该函数将被调用。所以密码
function printHelloWorld() {
console.log("Hello World")
}
firebase.auth().onAuthStateChanged(printHelloWorld)
将"Hello World"
打印到控制台,当auth状态发生变化时。但是,在以后的某个时候,我们希望停止该函数的执行,因为我们已经做了我们需要做的事情。如果您熟悉事件侦听器,它们使用一个模式来删除事件监听器,您可以调用类似于removeEventListener
的东西。但是firebase没有offAuthStateChanged
之类的。相反,onAuthStateChanged
函数向您返回一个函数,该函数取消订阅您最初给它的函数。首先,它不返回原始函数(本例中给出的函数是printHelloWorld
),而是返回一个可用于删除原始函数的新函数。
所以回到这个例子:
function printHelloWorld() {
console.log("Hello World")
}
var unsubscribe = firebase.auth().onAuthStateChanged(printHelloWorld)
// ... Sometime later when we are no longer interested in auth changes
unsubscribe();
// From this point forward, when the auth state changes, printHelloWorld will no longer be triggered.
最后,假设您只希望在更改后运行一个函数,但只运行一次。最简单的方法是让它运行一次,然后取消订阅。所以密码:
var unsubscribe = firebase.auth().onAuthStateChanged(() => {
console.log("Hello World")
unsubscribe()
})
这意味着当第一次状态发生变化时,我们将记录字符串,然后立即从进一步的更改中取消订阅。因此,通过从函数本身调用取消订阅,我们只是说,运行一次,然后删除自己。
另外,请注意,您可以在函数的开始或结束时调用取消订阅,这并不重要。整个函数体将与任何其他函数体一样执行。因此,调用取消订阅不会停止函数其余部分的执行,也不会停止类似的操作。
这就是为什么像
var unsubscribe = firebase.auth().onAuthStateChanged(() => {
unsubscribe()
// Lots of other code here...
});
是如此普遍的模式。
发布于 2019-03-19 16:39:22
如果您只想侦听用户的auth状态的变化,只需一次就必须这样做:
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if(unsubscribe) {
unsubscribe();
}
}
侦听器似乎运行了两次,第一次是在创建时,第二次是当用户实际更改其状态时。在第一次没有定义unsubscribe
时,您需要在运行它之前检查是否定义了它。
https://stackoverflow.com/questions/47043188
复制相似问题