javascript - 在状态更改之前调用我的函数

标签 javascript reactjs firebase google-cloud-firestore

我在 Reactjs 工作,我的数据库是 Firebase。

我正在尝试从我的数据库中检索数据,然后检查相关数据。

在顶部,我有 const [group, setGroup] = useState(null); 用于我的组数据。在我的 CheckGroupRelationship 函数中,如果使用组对象数据检查数据库。

最初我在数据库调用之后调用函数:

  const GetGroupInfo = async (uid) => {
    await props.firestore
      .collection("groups")
      .doc(uid)
      .get()
      .then(async (doc) => {
        if (!doc.exists) {
          console.log("No such document!");
        } else {
          setGroup({
            id: doc.data().id,
            ownerID: doc.data().ownerID,
            name: doc.data().name,
          });
        }
      })
      .catch((err) => {
        console.log("Error getting document", err);
      });
      CheckGroupRelationship();
  };

但是,我会收到错误“Group is null”。所以我将调用的函数移到了 setState 中:

  const GetGroupInfo = async (id) => {
    await props.firestore
      .collection("groups")
      .doc(id)
      .get()
      .then(async (doc) => {
        if (!doc.exists) {
          console.log("No such document!");
        } else {
          setGroup(
            {
              id: doc.data().id,
              ownerID: doc.data().ownerID,
              name: doc.data().name,
              bio: doc.data().bio,
            },
            CheckGroupRelationship()
          );
        }
      })
      .catch((err) => {
        console.log("Error getting document", err);
      });
  };

这仍然会导致“group is null”错误。我不确定在设置状态后我还能做些什么来调用要调用的函数。

最佳答案

简单的解决方案是使用 useEffect。在您的情况下,您可以这样做:

const [group, setGroup] = useState(null);
useEffect(() => {
  if (group) {
    CheckGroupRelationship()
  }
}, [group])

useEffect 在这里做的是等待 group 改变,当它改变时调用内部回调。在这种情况下,您将在那里更新组。希望对你有帮助,加油

关于javascript - 在状态更改之前调用我的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62523334/

相关文章:

html - 如何限制输入框只能输入数字?

javascript - 如何在加载页面时打开面板

reactjs - React 中 Mailchimp 订阅期间的脚本错误

javascript - 如何创建一个动态列表,其中的元素描述仅在单击元素时显示?

android - 应用程序关闭时 Firebase 是否同步记录的事件?

javascript - 如何修复 : Cannot read property 'GoogleAuthProvider' of undefined

javascript - 这个 setTimeout 是如何工作的?什么是 49221 以及 console.log.bind 是如何工作的?

javascript - 如何使用 jquery 更改类

javascript - 代码行换行在一个长的javascript对象中

java - 如何在Android中创建firebase后台服务?