reactjs 我想知道这个useEffect实际上是否只在useMemo中没有任何内容时运行

6tdlim6h  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(141)

所以,我想知道这是否有意义。我试图在使用Axios获取数据时缓存数据/用户,但仅当cachedUsers.length没有长度时才运行此useEffect。这有任何建议或有更好的方法吗?

import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const GetAllUsers = () => {
  const [fsUsers, setFsUsers] = useState([]);
  const [notFoundErr, setNotFoundErr] = useState("");
  const [loading, toggleLoading] = useState(true);
  const navigate = useNavigate();

  const cachedUsers = useMemo(() => fsUsers, [fsUsers]);

  // Gets all users in Firestore DB.
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        toggleLoading(true);
        const res = await axios({
          method: "GET",
          url: "http://localhost:4000/auth/api/firebase/users",
          validateStatus: (status) => {
            return status === 200 || status === 404;
          },
        });
        console.log(res.data);
        if (res && res.status === 200) {
          setFsUsers(res.data);
        } else if (res && res.status === 404) {
          setNotFoundErr("No users found.");
        }
      } catch (error) {
        console.error(error);
        navigate("/error500");
      } finally {
        toggleLoading(false);
      }
    };
    fetchUsers();
  }, [!cachedUsers.length]);

  return [cachedUsers, notFoundErr, loading];
};

export default GetAllUsers;
k5ifujac

k5ifujac1#

代码中的useMemo没有任何作用,因为你只是返回状态中的值(你可以直接使用它)。useMemo将在每次fsUsers更新时重新计算,所以除非你正在转换/规范化该数据,否则没有必要记忆。
useEffect方面,如果我理解正确的话,你想发出一次这个请求,所以你可以只使用一个空的依赖数组来在钩子挂载时发出API调用:

import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const GetAllUsers = () => {
  const [fsUsers, setFsUsers] = useState([]);
  const [notFoundErr, setNotFoundErr] = useState("");
  const [loading, toggleLoading] = useState(true);
  const navigate = useNavigate();

  // Gets all users in Firestore DB.
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        toggleLoading(true);
        const res = await axios({
          method: "GET",
          url: "http://localhost:4000/auth/api/firebase/users",
          validateStatus: (status) => {
            return status === 200 || status === 404;
          },
        });
        console.log(res.data);
        if (res && res.status === 200) {
          setFsUsers(res.data);
        } else if (res && res.status === 404) {
          setNotFoundErr("No users found.");
        }
      } catch (error) {
        console.error(error);
        navigate("/error500");
      } finally {
        toggleLoading(false);
      }
    };
    fetchUsers();
  }, []);

  return [cachedUsers: fsUsers, notFoundErr, loading];
};

export default GetAllUsers;

相关问题