为什么 currentUser.uid 是未定义的

10 浏览
0 Comments

为什么 currentUser.uid 是未定义的

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

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

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

我在另一个组件中使用了相同的方法来添加数据,它运行得很好。

为什么会这样?提前感谢。

0
0 Comments

为什么currentUser.uid未定义的原因是,如果在访问auth.currentUser时没有用户登录,auth.currentUser将为null。你的代码使用?操作符来"安全地"访问其属性,忽略了这种可能性。当你使用?时,如果前面的表达式为“假”,整个表达式将变为未定义。你的代码应该在假设有一个要使用的对象之前检查是否为null。

解决方法是,你应该在假设有一个要使用的对象之前检查是否为null。

const currentUser = auth.currentUser;
if (currentUser) {
    const uid = currentUser.uid;
}
else {
    // 如果没有用户登录,你想要做什么?
}

如果你需要等到用户实际登录后再执行代码,你应该使用一个auth状态观察器来获取一个回调,告诉你用户对象何时可用。

参考资料:[Typescript the safe navigation operator ( ?. ) or (!.) and null property paths](https://stackoverflow.com/questions/40238144)

0