[英]Reuse React.useCallback() function across multiple components
我有幾個組件都在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>
)
}
我想將這個 function 移到組件之外,以便我可以重新使用它,我認為它看起來像這樣:
const updateThing = React.useCallback(myFunction)
但是,它有一個dispatch
依賴項,我需要傳入並添加到依賴項數組中。
我怎樣才能打破這個 function 以供重用,同時還能從useCallback
獲得性能提升?
您可以編寫一個自定義鈎子,例如
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>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.