如何设置 useEffect 以在第一次使用 eslint-react-hooks 渲染时从 API 获取数据?

how to set an useEffect to fetch data from API at first render with eslint-react-hooks?

我需要调用两个函数来仅在第一次渲染时获取数据。我在这个项目上使用了 react-hooks。所以代码看起来像这样:

const Component = (props) => {

  // init
  useEffect(() => {

    const fetchA = async () => {
      await props.fetchA()
    };

    const fetchB = async () => {
      await props.fetchB()
    };

    fetchA();
    fetchB();
  }, []);
}

fetchAfetchB 是 redux 执行的操作,用于在 reducer 上发出请求和保存数据。
然后我将 eslint-react-hooks 添加到项目中。现在 eslint 警告我

Blockquote React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect.

唯一的方法是在 useEffect 依赖项之前的行上应用 // eslint-disable-next-line react-hooks/exhaustive-deps 吗?

它指出,如果 props.fetchA 和 props.fetchB 发生变化,您的代码未设置为随之更新。如果您绝对确定要忽略对 props.fetchA 和 props.fetchB 的更改,则可以添加 eslint-disable。

如果您想让您的代码在 props.fetchA 或 props.fetchB 更改时执行更新,请按照 lint 警告中的说明执行如下操作:

const { fetchA, fetchB } = props;
useEffect(() => {
  // i renamed these so as not to conflict with the outer variables. Feel free to choose different names.
  const a = async () => {/* fetchA() */};
  const b = async () => {/* fetchB() */};
  a();
  b();
}, [fetchA, fetchB]);

根据 fetchA 和 fetchB 在做什么,您可能需要一些清理逻辑来撤消第一次所做的操作,但我无法准确告诉您是什么,因为我不知道 fetchA 和fetchB 做。