usePersistFn
持久化 function 的 Hook
#代码演示
#基本用法
count: 0
持久化的函数参数
渲染次数:1
未持久化的函数参数
渲染次数:1
Live Editor
Copy
(() => {const Child = React.memo(({ showCount }) => {const renderCountRef = useRef(0)renderCountRef.current++return (<div><p>渲染次数:{ renderCountRef.current }</p><Button onClick={showCount}>展示父组件的 count</Button></div>)})return function Example() {const [count, setCount] = useState(0)const previousCount = usePersistFn(count)const showCountPersistFn = usePersistFn(() => {message.info(`count: ${count}`)})const showCount = useCallback(() => {message.info(`count: ${count}`)},[count])return (<div><div><p>count: { count }</p><Button onClick={() => setCount(count + 1)}>Add</Button></div><div style={{ marginTop: 20 }}><h4>持久化的函数参数</h4><Child showCount={showCountPersistFn} /></div><div style={{ marginTop: 20 }}><h4>未持久化的函数参数</h4><Child showCount={showCount} /></div></div>)}})()
#API
type usePersistFn = <T extends Function>(fn: T) => T