如何解决此“ React Hook useEffect缺少依赖项”警告?

时间:2019-10-01 15:15:23

标签: reactjs react-hooks eslint-plugin-react-hooks

这是我的文件:

// useFetcher.js
import { useEffect, useState } from "react";

export default function useFetcher(action) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);
  async function loadData() {
    try {
      setLoading(true);
      const actionData = await action();
      setData(actionData);
    } catch (e) {
      setError(e);
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => {
    loadData();
  }, [action]);
  return [data, loading, error];
}

在第21行,投诉以下内容:

React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)

我该如何解决?

2 个答案:

答案 0 :(得分:1)

最好的方法是在useEffect内定义异步函数:

export default function useFetcher(action) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  useEffect(() => {
    async function loadData() {
      try {
        setLoading(true);
        const actionData = await action();
        setData(actionData);
      } catch (e) {
        setError(e);
      } finally {
        setLoading(false);
      }
    }

    loadData();
  }, [action]);
  return [data, loading, error];
}

docs中的更多信息。

答案 1 :(得分:0)

loadData函数添加到useEffect中的数组中。这样可以消除投诉:

useEffect(() => {
  loadData();
}, [action, loadData]);