简体   繁体   English

React useCallback 设置依赖于在回调中调用的 function

[英]React useCallback setting dependency on a function called inside the callback

I'm working on a web app using react and saw this implemented there.我正在使用 react 开发 web 应用程序,并看到它在那里实现。 It goes something like this:它是这样的:

const onAddNewAccount = useCallback(async () => {
   await refetch();
   setOtherState((prev) => {...});
},
[refetch]);

I don't understand why do this, is this actually something correct?我不明白为什么要这样做,这实际上是正确的吗? Because from what I understand the callback will be called on one of the dependencies changing.因为据我了解,回调将在依赖项之一发生变化时被调用。

From what I've seen calling refetch won't actually trigger useCallback probably because it is just called right?从我所见,调用refetch实际上不会触发useCallback可能是因为它只是被调用了吗? not changed.没有改变。

So basically I need help understanding why they did this.所以基本上我需要帮助来理解他们为什么这样做。

the callback will be called on one of the dependencies changing.回调将在依赖项之一发生变化时被调用。

No, it won't be called, it will just be recreated.不,它不会被调用,它只会被重新创建。 The purpose of useCallback is to memoize the function and reuse it if nothing has changed. useCallback的目的是记住 function 并在没有任何变化的情况下重用它。 In other words, it's trying to make it so onAddNewAccount from render 1 === onAddNewAccount from render 2.换句话说,它试图从渲染 1 的onAddNewAccount === 来自渲染 2 的onAddNewAccount做到这一点。

If refetch changes, then the memoization will break and a new function is created.如果refetch更改,则 memoization 将中断并创建一个新的 function。 That way the new onAddNewAccount can call the new refetch if needed.这样,新的onAddNewAccount可以在需要时调用新的重新获取。 If refetch never changes, then that's great: the memoization can last forever then.如果refetch永远不会改变,那就太好了:memoization 可以永远持续下去。

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

相关问题 React.Js - 回调生成器中的 useCallback - React.Js - useCallback inside a callback generator “useState”不能在回调中调用。 如何在“useCallback”上使用 state? - “useState” cannot be called inside a callback. How to use state on “useCallback”? function prop 作为 useCallback 的依赖项 - function prop as dependency for useCallback React usecallback 不遵守由子函数引起的依赖项更改 - React usecallback not honoring dependency change caused by child function 反应:useCallback - useCallback 与空依赖数组 VS 根本不使用 useCallback - React: useCallback - useCallback with empty dependency array VS not using useCallback at all 在 useCallback() 钩子中反应 setState 没有正确设置状态变量? - React setState inside useCallback() hook not setting state variable correctly? React Native:state 在 useCallBack 钩子 function 内变得未定义 - React Native : state is getting undefined inside useCallBack hook function useCallback 中的生成器 function 在反应中返回相同的值,如何解决这个问题? - Generator function inside useCallback is returning same values in react, How to solve this? 反应 useEffect 和 useCallback linting 错误 - 缺少依赖项 - React useEffect and useCallback linting error - missing dependency React Hook useEffect/useCallback 缺少依赖项 - React Hook useEffect/useCallback has a missing dependency
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM