跨多个组件重用 React.useCallback() 函数

Ale*_*lex 2 javascript reactjs react-native react-hooks usecallback

我有几个组件都在onPress处理程序上调用相同的函数,假设它如下所示:

function MyComponent () {
  const dispatch = useDispatch()

  const updateThing = React.useCallback((thingId: string) => {
    dispatch(someActionCreator(thingId))
    someGlobalFunction(thingId)
  }, [dispatch])

  return (
    <View>
      <NestedComponent onUpdate={updateThing} />
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)

我想把这个函数移到组件之外,这样我就可以重新使用它,认为它看起来像这样:

const updateThing = React.useCallback(myFunction)
Run Code Online (Sandbox Code Playgroud)

但是,它有一个dispatch我需要传入并添加到依赖项数组的依赖项。

我怎样才能将这个函数分解出来以供重用,同时还能从中获得性能增益useCallback

Shu*_*tri 5

您可以编写一个自定义钩子,例如

export const useUpdateThinkg = () => {
  const dispatch = useDispatch()

  const updateThing = React.useCallback((thingId: string) => {
    dispatch(someActionCreator(thingId))
    someGlobalFunction(thingId)
  }, [dispatch])
  return { updateThing };
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

import { useUpdateThing } from 'path/to/updateThing'
function MyComponent () {
  const { updateThing} = useUpdateThing();

  return (
    <View>
      <NestedComponent onUpdate={updateThing} />
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)