简体   繁体   English

在更改 state 之前调用我的 function

[英]My function is being called before the state is changed

I'm working in Reactjs and my database is Firebase.我在 Reactjs 工作,我的数据库是 Firebase。

I'm trying to retrieve data from my database and then checking data regarding it.我正在尝试从我的数据库中检索数据,然后检查有关它的数据。

At the top, I have const [group, setGroup] = useState(null);在顶部,我有const [group, setGroup] = useState(null); for my group data.对于我的组数据。 In my CheckGroupRelationship function, if checks the database using the group object data.在我的 CheckGroupRelationship function 中,如果使用组 object 数据检查数据库。

Initially I had the function called after the database call:最初我在数据库调用后调用了 function:

  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();
  };

However, I would get the error "Group is null".但是,我会收到错误“组为空”。 So I moved the function called to the setState:所以我将调用的 function 移到了 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);
      });
  };

This would still result in the "group is null" error.这仍然会导致“组为空”错误。 I'm not sure what else I can do to get the function to be called AFTER the state is set.我不确定在设置 state 之后我还能做些什么来调用 function。

the easy solution would be to use useEffect .简单的解决方案是使用useEffect In your case you can do this:在您的情况下,您可以这样做:

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

What useEffect does here is waiting for group to change and when it changes it calls the inside callback. useEffect在这里所做的是等待group更改,当它更改时,它会调用内部回调。 In this case you will have group updated there.在这种情况下,您将在那里更新组。 Hope it helps, cheers希望有帮助,加油

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM