【问题标题】:Reuse React.useCallback() function across multiple components跨多个组件重用 React.useCallback() 函数
【发布时间】:2020-08-24 01:00:57
【问题描述】:

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

function MyComponent () {
  const dispatch = useDispatch()

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

  return (
    <View>
      <NestedComponent onUpdate={updateThing} />
    </View>
  )
}

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

const updateThing = React.useCallback(myFunction)

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

如何在从useCallback 获得性能提升的同时拆分此函数以供重复使用?

【问题讨论】:

    标签: javascript reactjs react-native react-hooks usecallback


    【解决方案1】:

    你可以写一个自定义的钩子

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

    然后像这样使用它

    import { useUpdateThing } from 'path/to/updateThing'
    function MyComponent () {
      const { updateThing} = useUpdateThing();
    
      return (
        <View>
          <NestedComponent onUpdate={updateThing} />
        </View>
      )
    }
    

    【讨论】:

    • 出色的答案 - 谢谢。习惯在 Hooks 中思考需要一段时间,但这是一个多么优雅的解决方案。 SO让我在几分钟后接受答案。
    • 很高兴帮助了 Alex :-) 是的,钩子是一个学习曲线
    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 2021-11-07
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多