简体   繁体   English

嗨,我正在从 firestore 检索数据,并检查是否将用户定向到索引页面或输入新用户的详细信息但无法这样做

[英]Hi, i'm retrieving data from firestore, and checking whether to direct the user to index page or to enter details for a new user But not able to do so

React code反应代码

    import React, { useEffect, useState } from "react";
    import { getDocs, collection } from "firebase/firestore";
    import { auth, db } from "../firebase-config";
    import { useNavigate } from "react-router-dom";
    
    function Load() {
      const navigate = useNavigate();
    
      const [accountList, setAccountList] = useState([]);
      const [hasEmail, setHasEmail] = useState(false);
      const accountRef = collection(db, "accounts");

Am i using useEffect correctly?我正确使用 useEffect 吗?

      useEffect(() => {
        const getAccounts = async () => {
          const data = await getDocs(accountRef);
          setAccountList(
            data.docs.map((doc) => ({
              ...doc.data(),
              id: doc.id,
            }))
          );
        };
        getAccounts();
        emailCheck();
        direct();
      }, []);

checking whether email exists检查 email 是否存在

      const emailCheck = () => {
        if (accountList.filter((e) => e.email === auth.currentUser.email)) {
          setHasEmail(true);
        } else {
          setHasEmail(false);
        }
      };

Redirecting based on current user根据当前用户重定向

      const direct = () => {
        if (hasEmail) {
          navigate("/index");
        } else {
          navigate("/enterdetails");
        }
      };
      return <div></div>;
    }

The code compiles but doesn't redirect properly to any of the pages.代码编译但没有正确重定向到任何页面。 What changes should I make?我应该做出哪些改变? First question posted excuse me if format is wrong.如果格式错误,请原谅我发布的第一个问题。

There are two problems here:这里有两个问题:

useEffect(() => {
  const getAccounts = async () => {
    const data = await getDocs(accountRef);
    setAccountList(
      data.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }))
    );
  };
  getAccounts();
  emailCheck();
  direct();
}, []);

In order:为了:

  1. Since getAccounts is asynchronous, you need to use await when calling it.由于getAccounts是异步的,调用的时候需要使用await
  2. But even then, setting state is an asynchronous operation too, so the account list won't be updated immediately after getAccounts completes - even when you use await when calling it.但即便如此, 设置 state 也是一个异步操作,因此在getAccounts完成后不会立即更新帐户列表 - 即使您在调用它时使用await也是如此。

If you don't use the accountList for rendering UI, you should probably get rid of it as a useState hook altogether, and just use regular JavaScript variables to pass the value around.如果您不使用accountList来呈现 UI,您可能应该完全摆脱它作为useState钩子,而只需使用常规 JavaScript 变量来传递值。

But even if you use it in the UI, you'll need to use different logic to check its results.但即使你在 UI 中使用它,你也需要使用不同的逻辑来检查它的结果。 For example, you could run the extra checks inside the getAccounts function and have them use the same results as a regular variable:例如,您可以在getAccounts function 中运行额外检查,并让它们使用与常规变量相同的结果:

useEffect(() => {
  const getAccounts = async () => {
    const data = await getDocs(accountRef);
    const result = data.docs.map((doc) => ({
      ...doc.data(),
      id: doc.id,
    }));
    setAccountList(result);
    emailCheck(result);
    direct();
  };
  getAccounts();
}, []);

const emailCheck = (accounts) => {
  setHasEmail(accounts.some((e) => e.email === auth.currentUser.email));
};

Alternatively, you can use a second effect that depends on the accountList state variable to perform the check and redirect:或者,您可以使用依赖于accountList state 变量的第二个效果来执行检查和重定向:

useEffect(() => {
  const getAccounts = async () => {
    const data = await getDocs(accountRef);
    setAccountList(
      data.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }))
    );
  };
  getAccounts();
});
useEffect(() => {
  emailCheck();
  direct();
}, [accountList]);

Now the second effect will be triggered each time the accountList is updated in the state.现在每次更新accountList中的 accountList 时都会触发第二个效果。

暂无
暂无

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

相关问题 从 firestore/firebase 检索当前用户数据时未定义 - Undefined while retrieving current user data from firestore/firebase 如何编写一个云 function,它在新用户通过身份验证后在 Firestore 数据库中创建一个用户? - How do I write a cloud function which creates a user in the Firestore database once a new user gets authenticated? 所以我试图在允许将帖子提交到我的 firebase 火库之前检查用户是否已登录 - So I'm trying to check if user is logged in before allowing a post to be submitted to my firebase firestore 如何根据 firestore 中的当前用户详细信息过滤数据 - how to filter data acording to current user details in firestore 从 Cloud Firestore 检索数据 - retrieving data from cloud firestore 使用 Cloud Functions 访问 firestore 中的用户数据,但如何安全地发送 UID/IDToken? - Accessing user data in firestore using Cloud Functions, but how do I securely send the UID/IDToken? 当我通过表单输入数据并提交时,firebase 获得了图像,但其他数据的详细信息没有出现在 Firestore collections - While I enter data through a form and submit , firebase gets the image but details of other data didn't get on the firestore collections 使用 React 和 Firestore 登录后如何通过 UID 获取用户详细信息? - How can I get user details by UID after login with React and Firestore? 如何将用户的 Firestore Map 读取为 Swift 字典? - How do I read a User's Firestore Map to a Swift Dictionary? 从 firebase firestore 检索数据列表时出错 - Error retrieving a list of data from firebase firestore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM