为什么带有空依赖项数组的useCallback不返回相同的函数?

我正在尝试编写一个自定义的React钩子,该钩子返回的函数在每次调用该钩子时都保持引用相等。意味着每次都从钩子返回完全相同的函数,因此将它们与===进行比较将返回true

我印象中useCallback hook是实现这一目标的方法:

function useCorrectCallback() {
  const [count,setCount] = useState(0)
  let increment = () => setCount(c => c + 1)

  let memoized = useCallback(increment,[])
  return {
    count,increment: memoized
  }
}

因此,当调用此钩子时,我相信每次返回值的increment属性应该是完全相同的函数。它应该是第一次运行该钩子时的内联函数的值,并且在以后的钩子执行中不要更改,因为我没有使用useCallback指定对[]的依赖。

但是这似乎没有发生!我已经写了test project来演示此问题。这是that test的症结所在:

function validateFunctionEquality(hookResult) {
  // Store the last result of running the hook
  let stored = { ...hookResult }

  // Force a re-render to run the hook again
  expect(hookResult.count).toEqual(0)
  act(hookResult.increment)
  expect(hookResult.count).toEqual(1)

  // Compare the previous results to the current results
  expect(hookResult.constant).toEqual(stored.constant)
  expect(hookResult.increment).toEqual(stored.increment)
}

只是为了验证我的测试是正确的,我还编写了一个钩子,该钩子仅使用全局范围的对象来维护“内存”,而不是尝试要求React使用useCallback进行操作。这个钩子通过了测试:

let memoryHack = {}

function useMemoryHack() {
  const [count,setCount] = useState(0)
  let increment = () => setCount(c => c + 1)

  memoryHack.increment = memoryHack.increment || increment
  return {
    count,increment: memoryHack.increment
  }
}

我使用useCallback的方式不正确吗?为什么useCorrectCallback在后​​续执行时会在其increment属性中返回不同的函数?

x357904377 回答:为什么带有空依赖项数组的useCallback不返回相同的函数?

我怀疑是enzyme浅薄的问题。可能与https://github.com/airbnb/enzyme/issues/2086

有关

通过使用mount,您的测试通过原样:

  act(() => {
    componentMount = mount( // used mount instead of shallow
      <Component>
        {hookValues => {
          copyHookValues(hookResult,hookValues)
          return null
        }}
      </Component>
    )
  })
本文链接:https://www.f2er.com/2687757.html

大家都在问