简体   繁体   English

React.useCallback:我是否需要将依赖项数组中的函数与依赖项一起传递?

[英]React.useCallback: do I need to pass functions in array of dependencies along with dependencies?

React docs example shows only [a, b] as dependencies. React 文档示例仅显示[a, b]作为依赖项。 Function doSomething is not passed.函数doSomething没有通过。

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

But later docs reads:但后来的文档写道:

every value referenced inside the callback should also appear in the dependencies array.回调中引用的每个值也应该出现在依赖项数组中。

My question: do I need to pass doSomething as well?我的问题:我还需要通过doSomething吗?

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b, doSomething],
);

Technically it's not required if it doesn't change, but it can bring unexpected behavior, so just for simplicity you need to pass all things you used inside if it's declared in component or comes from props.从技术上讲,如果它不更改,则不需要它,但它可能会带来意外行为,所以为了简单起见,如果它在组件中声明或来自 props,则需要传递你在内部使用的所有东西。 Also if you are using eslint, there is awesome plugin for hooks which is de-facto standard此外,如果您使用的是 eslint,则有一个很棒的钩子插件,它是事实上的标准

暂无
暂无

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

相关问题 React.useCallback() 用于链式匿名函数 - React.useCallback() for chained anonymous functions 反应挂钩useCallback没有依赖 - React hook useCallback without dependencies 如何使用 React.usecallback? - How to use React.usecallback? 无法读取 React 中 useEffect 或 useCallback 中的依赖项数组中未定义 Object 的属性 - Cannot Read Property of undefined Object in dependencies array in useEffect or useCallback in React 如何确定 React.useCallback 的依赖列表? - How to decide the dependency list for React.useCallback? 在 useCallback 中的数组依赖中的父方法 - Parent's methods in array dependencies in useCallback React Hook useCallback 收到一个依赖未知的函数。 改为传递内联函数 - React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead React useCallback 钩子:这些 handleChange 和 handleSubmit 函数的正确依赖项是什么,以防止重新渲染? - React useCallback hook: What are the correct dependencies for these handleChange & handleSubmit functions to prevent re rendering? TypeError: undefined is not a function(靠近'...(0,_react.useCallBack)...')。 我不知道我的代码中的 usCallBack() function 有什么问题 - TypeError: undefined is not a function (near '...(0, _react.useCallBack)...'). I don't know what's wrong with the usCallBack() function in my code 为什么 React.useCallback 触发重新渲染,你不应该? - Why does React.useCallback trigger rerender, thouh it should not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM