[英]Is there a way to avoid infinite loop of dependencies and to pass the correct dependencies to useEffect hook in this case?
我有一个自定义钩子,它作为 arguments 之一获得回调并在useEffect
中调用它
const customHook = (callback: Function) => {
...
useEffect(() => {
if (something) {
callback();
}
}, [other things, callback]);
return {values}
}
这里的问题是callback
是 function 并导致useEffect
在循环中运行。 useCallback
建议在父组件中使用 useCallback。 所以我决定将此callback
包装在我调用customHook
useCallback
。
所以我的组件中会有这样的东西:
const memoizedCallback = useCallback(() => {
myFunction(values);
}, [values, myFunction]);
const { values } = customHook(memoizedCallback);
在这里我有我的问题 - myFunction
的依赖项是从customHook
返回的,在它们定义之前我不能使用它们。 但是由于同样的原因,我也不能在customHook
调用之后放置memoizedCallback
。
现在我被困在这个无限循环的依赖中,如果不忽略 eslint 警告,我不知道如何解决这个问题。
因此,任何想法和解决方案将不胜感激:)
如果更改回调不应导致执行useEffect
块,请将callback
设置为 ref:
const customHook = (callback: Function) => {
const fn = useRef(callback);
...
useEffect(() => {
fn.current = callback;
})
useEffect(() => {
if (something) {
fn.current(); // fn.current?.() if fn.current might be undefined
}
}, [something]);
return {values}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.