[英]Reuse React.useCallback() function across multiple components
I have a few components that all call the same function on an onPress
handler, let's say it looks like the following:我有几个组件都在
onPress
处理程序上调用相同的 function,假设它如下所示:
function MyComponent () {
const dispatch = useDispatch()
const updateThing = React.useCallback((thingId: string) => {
dispatch(someActionCreator(thingId))
someGlobalFunction(thingId)
}, [dispatch])
return (
<View>
<NestedComponent onUpdate={updateThing} />
</View>
)
}
I want to move this function outside of the component so I can re-use it, thinking it would look something like this:我想将这个 function 移到组件之外,以便我可以重新使用它,我认为它看起来像这样:
const updateThing = React.useCallback(myFunction)
However, it has a dependency of dispatch
that I need to pass in and add to the dependency array.但是,它有一个
dispatch
依赖项,我需要传入并添加到依赖项数组中。
How can I break this function out for reuse while also getting the performance gain from useCallback
?我怎样才能打破这个 function 以供重用,同时还能从
useCallback
获得性能提升?
You can write a custom hook like您可以编写一个自定义钩子,例如
export const useUpdateThinkg = () => {
const dispatch = useDispatch()
const updateThing = React.useCallback((thingId: string) => {
dispatch(someActionCreator(thingId))
someGlobalFunction(thingId)
}, [dispatch])
return { updateThing };
}
And then use it like然后像这样使用它
import { useUpdateThing } from 'path/to/updateThing'
function MyComponent () {
const { updateThing} = useUpdateThing();
return (
<View>
<NestedComponent onUpdate={updateThing} />
</View>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.