第一次加载页面加载时,React使用效应正在返回空数据

发布于 2025-02-06 23:51:05 字数 1730 浏览 2 评论 0 原文

我是通过使用效率对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函数正在抛出错误。但是,如果我再次提交,则随着数据填充而起作用。

要在第一页加载上获取数据,该怎么办?

I am making an API call to firebase from useEffect and the data returned is empty when the page loads for the first time but gets populated if I make any changes to the code and save it.
I want the data to be present when the page loads for the first time.

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

enter image description here

Because the data returned is empty, map function is throwing an error. But if I submit again it works as the data gets populated.

What should I change for the data to be fetched on the first page load?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

油饼 2025-02-13 23:51:05

在React中设置状态就像异步函数。
这意味着当您设置状态并在其之后放置 console.log 时,它可能会在状态实际完成更新之前运行。

这就是为什么我们具有使用的原因,这是一个内置的react钩子,当它的依赖项之一更改时,它会激活回调。

示例:

useEffect(() => {
   console.log(users)
   // Whatever else we want to do after the state has been updated.
}, [users])

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:

useEffect(() => {
   console.log(users)
   // Whatever else we want to do after the state has been updated.
}, [users])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "users" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info.

給妳壹絲溫柔 2025-02-13 23:51:05

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文