我是 React/Javascript 的新手,虽然我对钩子和异步函数的工作原理不太了解,但我有点困惑为什么我从我的一个数据库函数中得到
undefined
这是有问题的数据库函数:
async function readFromDB(ID, itemToGrab, type) {
const dbRef = ref(getDatabase());
const snapshot = await get(
child(dbRef, `users/` + type + `/${ID}${itemToGrab}`),
);
if (snapshot.exists()) {
return snapshot.val();
} else {
console.log("No data available");
}
}
这工作得很好,因为最终它确实从数据库中得到了我需要的东西。
现在我在这里使用这个函数来对用户进行检查。如果两个数据库请求都返回未定义(提供的用户尚未注册宠物),则他们还不是宠物主人,否则,他们是宠物主人:
async function check() {
if (
(await readFromDB(key, '/Pname', type)) === undefined &&
(await readFromDB(key, '/pets', 'dog-walkers')) === undefined
) {
console.log('user is not actually a owner yet!');
return 'notOwner';
} else {
console.log('user is a owner!');
return 'owner';
}
}
然后我这样调用这个检查函数:
const [result, setResult] = useState('');
useEffect(() => {
const fetchData = async () => {
let data = await check();
setResult(data);
console.log(data + ' DATA');
};
fetchData();
}, []);
然后像这样使用
result
:
return (
<>
{result === 'owner' ? (
<p>Owner</p>
) : result === 'notOwner' ? (
<p>notOwner</p>
) : (
<p>Loading Page</p>
)}
</>
);
当我测试功能时,我确保我使用的用户在其收藏中拥有宠物,这应该将状态设置为
owner
,但是,状态始终设置为notOwner
,因为数据库函数总是首先返回 undefined
,但是当页面重新加载时,它会正确加载 owner
页面。
我虽然拥有
async/await
应该让程序在运行 if 语句返回值之前等待数据库的响应。
我发现我的数据库函数应该在 else 块内有一个返回值。这似乎有效,因为现在网页在初始渲染上正确加载。这是更新的功能:
async function readFromDB(ID, itemToGrab, type) {
const dbRef = ref(getDatabase());
const snapshot = await get(
child(dbRef, `users/` + type + `/${ID}${itemToGrab}`),
);
if (snapshot.exists()) {
return snapshot.val();
} else {
console.log("No data available");
return 'noData'
}
}