firebase 如何从if语句导出const/let?

np8igboo  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(98)

我遇到了一个问题,auth.currentUser.uid最初= null,并且uid仅在几秒钟后加载,但是站点有时间陷入错误,我发现如果您将常量等同于auth.currentUser.uid,那么它将被更新并工作,但问题是userUID仅在if语句中更改,我需要全局更改它

if (auth.currentUser != null) {
    let userUID = (auth.currentUser.uid);
  };


  console.log(userUID);


  useEffect(() => {

    const q = query(collection(db, "customers", auth.currentUser.uid, "subscriptions"));

    onSnapshot(q, (querySnapshot) => {
      querySnapshot.forEach(async (subscription) => {
          setSubscription({
            role: subscription.data().role,
            current_period_start:
              subscription.data().current_period_start.seconds,
            current_period_end: subscription.data().current_period_end.seconds,
          });
        });
      });
    }, [auth.currentUser.uid]);
apeeds0o

apeeds0o1#

如果你的用户ID更新了,你可以试试这个方法,然后它运行查询,并且它会根据用户更改的值工作。

useEffect(() => {

if(auth.currentUser.uid){
    const q = query(collection(db, "customers", auth.currentUser.uid, "subscriptions"));

    onSnapshot(q, (querySnapshot) => {
      querySnapshot.forEach(async (subscription) => {
          setSubscription({
            role: subscription.data().role,
            current_period_start:
              subscription.data().current_period_start.seconds,
            current_period_end: subscription.data().current_period_end.seconds,
          });
        });
      });
}
}, [auth.currentUser.uid]);

相关问题