在useEffect中添加缺少的依赖项会导致递归循环

时间:2019-10-01 17:02:26

标签: reactjs react-hooks

当我尝试运行如下所示的代码时,出现警告提示React Hook useEffect has a missing dependency: 'userApi'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)

const userApi = useFetch();

useEffect(() => {
  userApi.run("/api/user");
}, []);

但是,如果我将userApi添加为依赖项,则会得到递归循环。 如果我忽略警告,一切都很好。 我应该忽略它吗?

这是我的useFetch钩子:

const useFetch = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const auth = useAuth();

  const run = async (url, method = "GET", data, options) => {
    setError();
    setIsLoading(true);
    try {
      const token = await auth.user.getIdToken();

      if (!options)
        options = {
          method,
          headers: {
            "Content-Type": "application/json"
          }
        };

      if (!options.headers) options.headers = {};
      if (!options.headers["Authorization"])
        options.headers["Authorization"] = `Bearer ${token}`;

      if (!options.body && data) options.body = JSON.stringify(data);

      const response = await fetch(url, options);
      console.log(response);
      if (!response.ok) throw Error(response.statusText);
      const json = await response.json();
      setData(json);
    } catch (e) {
      console.log(e);
      setError(e.message);
    }
    setIsLoading(false);
  };

  return { data, error, isLoading, run };
};

更新,我的工作代码:

const [getUser, { data: user, error, loading }] = useFetch("/api/user");

useEffect(() => {
  getUser();
}, [getUser]);

获取挂钩:

const useFetch = (url, method = "GET") => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);
    const { user } = useAuth();

    const run = useCallback(
        async (data, options) => {
          ...code...
        },
        [user, method, url]
    );
    return [run, { data, error, loading }];
};

1 个答案:

答案 0 :(得分:1)

您可以通过使用toStringlibrary(stringr) library(dplyr) library(purrr) df %>% mutate(newtext = map_chr(str_extract_all(text, str_c(fruit, collapse='|')), ~toString(unique(.x))) 添加一些备注来更新useFetch代码(也许还有useAuth)来解决问题,例如:

useMemo

还有

useCallback