我在 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/