第一次加载页面加载时,React使用效应正在返回空数据
我是通过使用效率对Firebase进行API调用,并且第一次加载页面时返回的数据为空,但是如果我对代码进行任何更改并保存,则填充了。 我希望在第一次加载页面时存在数据。
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [users, setUsers] = useState({});
const [status, setStatus] = useState({});
const userDetailsRef = collection(db, "userDetails");
const userStatusRef = collection(db, "userStatus");
const handleSubmit = (event) => {
event.preventDefault();
users.map((user) => {
if (email === user.email && password === user.password) {
getEmail();
}
});
};
const getEmail = async () => {
const data = await getDocs(userStatusRef);
setStatus(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
console.log(status);
status.map((em) => {
if (email === em.email) {
updateStatus(em.id);
}
});
};
const updateStatus = async (id) => {
const userDoc = doc(db, "userStatus", id);
const status = { status: "online" };
await updateDoc(userDoc, status);
console.log("updated status");
};
useEffect(() => {
getUsers();
}, []);
const getUsers = async () => {
const data = await getDocs(userDetailsRef);
setUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
console.log(users);
};
由于返回的数据为空,因此MAP函数正在抛出错误。但是,如果我再次提交,则随着数据填充而起作用。
要在第一页加载上获取数据,该怎么办?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在React中设置状态就像异步函数。
这意味着当您设置状态并在其之后放置
console.log
时,它可能会在状态实际完成更新之前运行。这就是为什么我们具有
使用
的原因,这是一个内置的react钩子,当它的依赖项之一更改时,它会激活回调。示例:
此
console.log
只有在状态完成更改并发生渲染后才会运行。检查文档以获取更多信息。
Setting the state in React acts like an async function.
Meaning that the when you set the state and put a
console.log
right after it, it will likely run before the state has actually finished updating.Which is why we have
useEffect
, a built-in React hook that activates a callback when one of it's dependencies have changed.Example:
This
console.log
will run only after the state has finished changing and a render has occurred.Check the documentation for more info.
SetState
是异步的,无法保证状态将在您的日志点击时设置。请参阅:
状态看起来要正确设置,您的日志语句可能不会反映未决的状态更改。
setState
is asynchronous, there's no guarantees that the state will be set by the time your log is hit.See: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
The state looks to be set correctly, your log statement just might not reflect pending state changes.