首页 > 解决方案 > 仅在定义对象时如何运行 useEffect (和云 Firestore 查询)?

问题描述

尝试仅在定义“用户”时运行火库“onSnapshot”。起初,用户是一个空对象,后来它变成了一个带有id,名称等的对象。所以这不应该运行......但似乎这个'if'语句不起作用(firestore onSnapshot甚至会运行如果它未定义)。

如何解决这个问题?

  useEffect(() => {
    if (user) { //object is undefined at first, but gets defined later
      const unsubscribe = firebase
        .firestore()
        .collection('users')
        .doc(user.id) //This seems to run even when 'user' is undefined (an empty object)
        .onSnapshot(snapshot => {
           //...
        })

      return () => {
        unsubscribe()
      }
    }
  }, [])

标签: javascriptreactjsgoogle-cloud-firestore

解决方案


只需将user作为依赖项包含在您的 useEffect 挂钩中

 useEffect(() => {
    if (user) {
      //object is undefined at first, but gets defined later
      const unsubscribe = firebase
        .firestore()
        .collection("users")
        .doc(user.id) //This seems to run even when 'user' is undefined (an empty object)
        .onSnapshot(snapshot => {
          //...
        });

      return () => {
        unsubscribe();
      };
    }
  }, [user]);

推荐阅读