使用 useEffect 给出多个数组,使用数组中的值

Using values from an array using useEffect giving multiple arrays

我正在尝试从数据库中提取数据并将数据库中的值与登录用户进行比较。我用来检查的代码如下所示:

  const [records, setRecords] = useState([]);
  const [email, SetEmail] = useState([]);

  // This method fetches the records from the database.
  useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/admin/`);

      if (!response.ok) {
        const message = `An error occurred: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const admin = await response.json();
      setRecords(admin);
      let emailList = [];
      admin.forEach((x) => {
        emailList.push(x.email);
        return emailList;
      }, SetEmail(emailList));
    }

    getRecords();

    return () => {

    };
  }, []);
  console.log(email);
  console.log(email.includes("xxx@yahoo.com"));

这个问题是 console.log(email) returns 在返回完全附加的数组之前有多个空数组,这样如果我将当前登录的电子邮件与数据库中的电子邮件进行比较,我就会得到- 假的,假的.. 真的。使我的组件不可修改。

我需要改用 map() 函数

由于您要将 1 个数组转换为具有相同条目数的另一个数组,因此您可以使用映射。

也将 console.log 视为副作用并将它们放在 useEffects

  const [records, setRecords] = useState([]);
  const [email, SetEmail] = useState([]);

  // This method fetches the records from the database.
  useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/admin/`);

      if (!response.ok) {
        const message = `An error occurred: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const admin = await response.json();
      
      const emailList = admin.map(x => x.email);
      setRecords(admin);
      SetEmail(emailList));
    }

    getRecords();

    return () => {

    };
  }, []);

  useEffect(() => {
      console.log(email);
      console.log(email.includes("xxx@yahoo.com"));
  },[email]);