[英]Is there a way to memoize a function passed from params - (useCallback) exhaustive-deps
So I have this little snippet:所以我有这个小片段:
const useTest = (callbackFunc) => {
const user = useSelector(selector.getUser); // a value from store
useEffect(() => {
if (user.id === 1) {
callbackFunc()
}
}, [callbackFunc, user.id])
}
On the code above if callbackFunc
is not memoized (wrapped in useCallback) before passing, the useEffect
will trigger an infinite loop.在上面的代码中,如果
callbackFunc
在传递之前没有被记忆(包装在 useCallback 中), useEffect
将触发一个无限循环。
Wrapping the function on a useCallback inside the hook will still trigger an infinite loop, so that's a no:将函数包装在钩子内的 useCallback 上仍会触发无限循环,因此不能:
const cb = () => useCallback(() => callbackFunc, [callbackFunc]);
The above will trigger infite loop because callbackFunc
.以上将触发无限循环,因为
callbackFunc
。
YES I am well aware that I can just wrap the function inside useCallback
before passing to this hook, my only problem with that is: there will be a high probability that other/future devs will just pass a non-memoized function when calling this hook and this is what worries me.是的,我很清楚我可以在传递给这个钩子之前将函数包装在
useCallback
,我唯一的问题是:其他/未来的开发人员在调用这个钩子时很可能只会传递一个非记忆化的函数而这正是我所担心的。 ` `
I can't remove the callbackFunc
on the useEffect
/ useCallback
second parameter array because of exhaustive-deps
rule - and removing it (or on this line) is also prohibited by the higher devs.由于
exhaustive-deps
规则,我无法删除useEffect
/ useCallback
第二个参数数组上的callbackFunc
- 更高的开发人员也禁止删除它(或在这条线上)。
Any idea how can I possibly achieve my goal?知道我怎样才能实现我的目标吗? If none thatn I'll just pray that other devs will read the hook first before using it.
如果没有,那么我会祈祷其他开发人员在使用之前先阅读钩子。
You can do something like this, but you won't be able to modify the callback anymore你可以做这样的事情,但你将无法再修改回调
const funcRef = React.useRef(null)
useEffect(() => {
funcRef = callbackFunc
}, [])
useEffect(() => {
if (funcRef.current){
if (user.id === 1) {
funcRef.current()
}
}
}, [funcRef, user.id])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.