|
| 1 | +import { supportRef } from 'rc-util/lib/ref'; |
| 2 | +import * as React from 'react'; |
| 3 | + |
| 4 | +const RenderContext = React.createContext<number>(0); |
| 5 | + |
| 6 | +export function makeImmutable<T extends React.ComponentType<any>>(Component: T): T { |
| 7 | + const refAble = supportRef(Component); |
| 8 | + |
| 9 | + const ImmutableComponent = function (props: any, ref: any) { |
| 10 | + const refProps = refAble ? { ref } : {}; |
| 11 | + const renderTimesRef = React.useRef(0); |
| 12 | + renderTimesRef.current += 1; |
| 13 | + |
| 14 | + return ( |
| 15 | + <RenderContext.Provider value={renderTimesRef.current}> |
| 16 | + <Component {...props} {...refProps} /> |
| 17 | + </RenderContext.Provider> |
| 18 | + ); |
| 19 | + }; |
| 20 | + |
| 21 | + if (process.env.NODE_ENV !== 'production') { |
| 22 | + ImmutableComponent.displayName = `ImmutableRoot(${Component.displayName || Component.name})`; |
| 23 | + } |
| 24 | + |
| 25 | + return refAble ? React.forwardRef(ImmutableComponent) : (ImmutableComponent as any); |
| 26 | +} |
| 27 | + |
| 28 | +export function responseImmutable<T extends React.ComponentType<any>>(Component: T): T { |
| 29 | + const refAble = supportRef(Component); |
| 30 | + |
| 31 | + const ImmutableComponent = function (props: any, ref: any) { |
| 32 | + const refProps = refAble ? { ref } : {}; |
| 33 | + const renderTimes = React.useContext(RenderContext); |
| 34 | + |
| 35 | + return React.useMemo(() => <Component {...props} {...refProps} />, [renderTimes]); |
| 36 | + }; |
| 37 | + |
| 38 | + if (process.env.NODE_ENV !== 'production') { |
| 39 | + ImmutableComponent.displayName = `ImmutableResponse(${ |
| 40 | + Component.displayName || Component.name |
| 41 | + })`; |
| 42 | + } |
| 43 | + |
| 44 | + return refAble ? React.forwardRef(ImmutableComponent) : (ImmutableComponent as any); |
| 45 | +} |
0 commit comments