通过 onClick 调用方法来响应 useMemo

myT*_*532 1 reactjs

我在使用 React useMemo 和 onClick 调用函数时遇到问题。它说我需要添加该函数作为 useMemo 依赖项,但是当我添加它时,该函数会使 useMemo Hook 在每次渲染时发生变化。

const test = useMemo(() => {
   return myData.map((obj, index) => {
      return (
        <div key={index}>
           <button type="button" onClick={() => myFunc(index)}>Test</button>
        </div>
      )
   });
}, [myData]);
Run Code Online (Sandbox Code Playgroud)

它返回警告:React Hook useMemo has a missing dependency: 'myFunc'. Either include it or remove the dependency array

我尝试将其包含在依赖项中[myData, myFunc]。然后,它返回:The 'myFunc' function makes the dependencies of useMemo Hook (at line 105) change on every render. Move it inside the useMemo callback. Alternatively, wrap the definition of 'myFunc' in its own useCallback() Hook

我该如何解决这个问题?

谢谢

e.a*_*.a. 5

共有三种情况;如果您的函数不依赖于组件内的任何状态(即它没有副作用),那么您可以将其设为纯函数并将其放在组件定义之外;但如果确实如此,则有两种情况:要么您的函数仅在 useMemo 挂钩内被调用,在这种情况下您可以将函数定义放在那里,如下所示:

const test = useMemo(() => {
   const myFunc = () => {}
   return myData.map((obj, index) => {
      return (
        <div key={index}>
           <button type="button" onClick={() => myFunc(index)}>Test</button>
        </div>
      )
   });
}, [myData]);
Run Code Online (Sandbox Code Playgroud)

但是如果你想把它放在 useMemo 之外并在该组件内的任何地方调用它(或者可能将其传递给子组件),只需将它包装在 useCallback 钩子中,这样它就不会在每次渲染时重新声明并且不会改变依赖数组。这样你就不会改变 useMemo 钩子中的任何内容,只需像这样包装你的 myFunc 函数:

const MemoizedMyFunct = useCallback(
// put your function definition here
, [
// fill the dependency array with the variables used inside your function
])
Run Code Online (Sandbox Code Playgroud)