为什么currentUser.uid未定义

时间:2020-10-01 16:53:49

标签: reactjs typescript firebase firebase-authentication

我正在尝试将信息添加到当前登录用户的文档中。

我的组件中有以下代码片段-

console.log("user", auth.currentUser?.uid);

  useEffect(() => {
    if (productId) {
      db.collection("users")
        .doc(auth.currentUser?.uid)
        .collection("cart")
        .doc(productId)
        .onSnapshot((snapshot) => setProduct(snapshot.data()));
    }
  }, []);

在这里

const auth = firebase.auth();

控制台日志实际上为我提供了用户的uid,但是下面的钩子产生了错误-

FirebaseError:函数CollectionReference.doc()要求其第一个参数的类型为非空字符串,但是它是:undefined

我在另一个组件中使用了相同的方法来添加数据,并且效果很好。

为什么会这样?预先感谢。

1 个答案:

答案 0 :(得分:2)

如果

auth.currentUser在访问时没有用户登录,则将为null。您的代码通过使用?运算符来“安全”访问其属性,从而盲目地忽略了这种可能性。当您使用?时,如果先前的表达式为“ falsy”,则整个表达式将变得不确定。相反,您的代码应该在假定要使用的对象之前检查null。

const currentUser = auth.currentUser
if (currentUser) {
    const uid = currentUser.uid;
}
else {
    // what do you want to do if there is no one signed in?
}

如果需要等到用户实际登录后,则应使用auth state observer来获取一个回调,该回调告诉您该用户对象何时可用。

另请参阅:Typescript the safe navigation operator ( ?. ) or (!.) and null property paths