简体   繁体   English

第一次加载页面时,React useEffect 返回空数据

[英]React useEffect is returning empty data when page loads for the first time

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.我正在从 useEffect 对 firebase 进行 API 调用,当页面第一次加载时返回的数据为空,但如果我对代码进行任何更改并保存它就会填充。 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);
    };

在此处输入图像描述

Because the data returned is empty, map function is throwing an error.因为返回的数据为空,map function 报错。 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?对于要在第一页加载时获取的数据,我应该更改什么?

Setting the state in React acts like an async function.在 React 中设置 state 就像一个异步 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.这意味着当您设置 state 并在其后放置一个console.log时,它可能会在 state 实际完成更新之前运行。

Which is why we have useEffect , a built-in React hook that activates a callback when one of it's dependencies have changed.这就是为什么我们有useEffect ,一个内置的 React 钩子,当它的一个依赖项发生变化时激活回调。

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.console.log仅在 state 完成更改并发生渲染后才会运行。

  • Note: "users" in the example is interchangeable with whatever other state piece you're dealing with.注意:示例中的“用户”可与您正在处理的任何其他 state 部分互换。

Check the documentation for more info.查看文档以获取更多信息。

setState is asynchronous, there's no guarantees that the state will be set by the time your log is hit. setState是异步的,不能保证 state 会在您的日志被命中时设置。

See: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous请参阅: 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. state 看起来设置正确,您的日志语句可能不会反映挂起的 state 更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 第一次加载页面时,React useEffect 返回空数据数组 - React useEffect is returning empty data array when page loads for the first time 首次加载页面时未定义 firebase 和 nextjs 的 useEffect - useEffect with firebase and nextjs undefined when page first loads Firestore 查询在页面首次加载时没有得到结果,但在页面重新呈现时 - React Native - Firestore query not getting results when page first loads, but is when page re-renders - React Native React-Firebase:为什么页面在第一次加载时失败,但在刷新时加载正确? - React-Firebase: Why does page fail on first load, but then loads properly on refresh? React 和 Firebase Firestore V9 上一页分页返回“第一页” - React and Firebase Firestore V9 Previous Page Pagination returning to "first page" 首次使用 navigation.navigate 加载页面时未获取 currentUser.uid - Not getting currentUser.uid when the page first loads using navigation.navigate 为什么recyclerview数据只有在第二次点击按钮时才加载 - Why does the recyclerview data loads only when the button is clicked the second time Promise 存在数据时从 Firestore 返回空值 - Promise returning empty value from Firestore when data is present useEffect 中的数据究竟如何影响页面加载 - How exactly data in useEffect work on page load 刷新页面时 useEffect 不需要的副作用 - useEffect unwanted side effect when refresh page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM