排除这个 useEffect 依赖数组变量是否明智? lint 推荐 3,但我只想依赖 1

Wise to exclude this useEffect dependency array variable? lint recommends 3, but i only want to depend on 1

我打算排除这个,但只是想仔细检查一下是否没有更好的方法。

因此我计划禁用此行的详尽描述。

这明智吗?

useEffect(() => {
    async function handleViews() {
      await sendViews(views, user, cancelToken);
      ... do more
    }
    if (
      appStateVisible.match('inactive') ||
      appStateVisible.match('background')
    ) {
      handleViews();
    }
  }, [appStateVisible]);

没有。您有几个首选的解决方案来忽略该规则。

你可以提供一个参考稳定值。我有时喜欢使用 useGetter 类型的钩子:

const useGetter = <S>(value: S): (() => S) => {
  const ref = useRef(value);
  useLayoutEffect(() => {
    ref.current = value;
  });
  return useCallback(() => ref.current, [ref]);
};

它允许你写这样的东西:

const getViewData = useGetter({ user, cancelToken })

useEffect(() => {
    async function handleViews() {
      const { user, cancelToken } = getViewData()
      const user = await sendViews(views, user, cancelToken);
      ... do more
    }
    if (
      appStateVisible.match('inactive') ||
      appStateVisible.match('background')
    ) {
      handleViews();
    }
}, [appStateVisible, getViewData]);

因为getViewData没有改变,useEffect 不会因为应用程序状态改变之外的任何其他原因被触发。 return 值不会过时。

作为替代方案,您可以正常提供所有依赖项,但这次您自己检查 appStateVisible 是否已更改。像 usePrevious 这样仅引用先前值的挂钩对于检查 previousAppStateVisible !== undefined && appStateVisible !== previousAppStateVisible 值是否从上次渲染发生变化很有用。如果没有,你可以 return 早点。 ( https://usehooks.com/usePrevious/ )