![](/img/trans.png)
[英]typescript es-lint error: react-hooks/exhaustive-deps
[英]Is secure to ignore the missing dependencies es-lint warning on react hooks?
我有一个组件需要在卸载时调用一个函数。 这个函数作为组件的一个prop
传递。 据我所知,要在组件卸载时调用函数,您只需要一个带有空依赖项数组的useEffect
:
useEffect(() => {
return () => { prop.onUnmount() }
}, []);
这按预期工作,但是 ESLint 抱怨缺少对钩子的依赖:
第 156:6 行:React Hook useEffect 缺少依赖项:'props.onUnmount'。 包括它们或删除依赖数组 react-hooks/exhaustive-deps
然而,这两种解决方案都不起作用,
prop.onUnmount()
在任何重新渲染时都没有改变并且钩子不应该被触发,它仍然执行return
部分。 因此该函数在卸载之前被调用。那么,忽略警告是否安全,或者是否有任何解决方法来执行该函数并阻止 ESLint 发出警告?
useEffect(() => {
return () => { prop.onUnmount() }
}, []);
这将运行第一次渲染时存在的 prop.onUnmount 函数。 因此,如果该 prop 在组件的生命周期中发生变化,您的代码将忽略该更改,这就是 lint 规则警告您的内容。
如果要运行上次渲染中存在的 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();
}
}, []);
如果您发现自己经常这样做,您可能希望将其提取到自定义钩子中,如下所示:
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.