简体   繁体   English

忽略反应钩子上缺少的依赖项 es-lint 警告是否安全?

[英]Is secure to ignore the missing dependencies es-lint warning on react hooks?

I have a component which needs to call a function when is unmounted.我有一个组件需要在卸载时调用一个函数。 This function is passed as a prop of the component.这个函数作为组件的一个prop传递。 As far as I know, to call a function on component unmount you only need a useEffect with an empty dependency array:据我所知,要在组件卸载时调用函数,您只需要一个带有空依赖项数组的useEffect

useEffect(() => {
    return () => { prop.onUnmount() }

}, []);

This works as expected, however ESLint complains about a missing dependency on the hook:这按预期工作,但是 ESLint 抱怨缺少对钩子的依赖:

Line 156:6: React Hook useEffect has missing dependencies: 'props.onUnmount'.第 156:6 行:React Hook useEffect 缺少依赖项:'props.onUnmount'。 Either include them or remove the dependency array react-hooks/exhaustive-deps包括它们或删除依赖数组 react-hooks/exhaustive-deps

However, neither solutions works,然而,这两种解决方案都不起作用,

  • If I remove the dependency array, the hook will be executed on each re render如果我删除依赖数组,钩子将在每次重新渲染时执行
  • If add the dependency, despite of prop.onUnmount() does not change on any rerender and the hook should not be triggered, it stills executing the return part.如果添加依赖,尽管prop.onUnmount()在任何重新渲染时都没有改变并且钩子不应该被触发,它仍然执行return部分。 So the function gets called before the unmount.因此该函数在卸载之前被调用。

So, is it safe to ignore the warning or is there any work around to execute the function and prevent ESLint to warn about it?那么,忽略警告是否安全,或者是否有任何解决方法来执行该函数并阻止 ESLint 发出警告?

useEffect(() => {
    return () => { prop.onUnmount() }
}, []);

This will run the prop.onUnmount function that existed on the very first render.这将运行第一次渲染时存在的 prop.onUnmount 函数。 So if that prop changes during the life of the component, your code will ignore that change, which is what the lint rule is warning you about.因此,如果该 prop 在组件的生命周期中发生变化,您的代码将忽略该更改,这就是 lint 规则警告您的内容。

If you want to run the prop.onUnmount that exists on the last render, then you'll need to do the following:如果要运行上次渲染中存在的 prop.onUnmount,则需要执行以下操作:

const cleanup = useRef();
// update the ref each render so if it changes the newest
//   one will be used during unmount
cleanup.current = prop.onUnmount;
useEffect(() => {
  return () => {
    cleanup.current();
  }
}, []);

If you find yourself doing this a lot, you may want to extract it to a custom hook, as in:如果您发现自己经常这样做,您可能希望将其提取到自定义钩子中,如下所示:

export const useUnmount = (fn) => {
  const fnRef = useRef();
  fnRef.current = fn;
  useEffect(() => {
    return () => {
      fnRef.current();
    }
  }, []);
};

// used like: 
useUnmount(props.onUnmount);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM