【问题标题】:My function is being called before the state is changed我的函数在状态改变之前被调用
【发布时间】:2020-10-12 20:10:11
【问题描述】:

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

但是,我会收到“组为空”错误。所以我把调用的函数移到了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);
      });
  };

这仍会导致“组为空”错误。我不确定在设置状态后我还能做些什么来调用函数。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

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

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

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

    【讨论】:

    • 这对我有用,尽管我必须进行一些更改。我添加了一个“if (groupLoaded === false)”标志以防止 useEffect 不断调用数据库,一旦 CheckGroupRelationship 完成,我将其更改为 true
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多