fix: hoc 组件缓存

This commit is contained in:
rainke 2023-10-17 17:33:07 +08:00 committed by 刘菊萍(絮黎)
parent a96961f588
commit 7677ad0166
2 changed files with 20 additions and 4 deletions

View File

@ -2,7 +2,12 @@ import { cloneEnumerableProperty } from '@alilc/lowcode-utils';
import adapter from '../adapter'; import adapter from '../adapter';
import { IBaseRendererInstance, IRendererProps } from '../types'; import { IBaseRendererInstance, IRendererProps } from '../types';
function patchDidCatch(Comp: any, { baseRenderer }: { baseRenderer: IBaseRendererInstance }) { interface Options {
baseRenderer: IBaseRendererInstance;
schema: any;
}
function patchDidCatch(Comp: any, { baseRenderer }: Options) {
if (Comp.patchedCatch) { if (Comp.patchedCatch) {
return; return;
} }
@ -44,7 +49,9 @@ function patchDidCatch(Comp: any, { baseRenderer }: { baseRenderer: IBaseRendere
} }
} }
export function compWrapper(Comp: any, options: { baseRenderer: IBaseRendererInstance }) { const cache = new Map();
export function compWrapper(Comp: any, options: Options) {
const { createElement, Component, forwardRef } = adapter.getRuntime(); const { createElement, Component, forwardRef } = adapter.getRuntime();
if ( if (
Comp?.prototype?.isReactComponent || // react Comp?.prototype?.isReactComponent || // react
@ -54,6 +61,11 @@ export function compWrapper(Comp: any, options: { baseRenderer: IBaseRendererIns
patchDidCatch(Comp, options); patchDidCatch(Comp, options);
return Comp; return Comp;
} }
if (cache.has(options.schema.id)) {
return cache.get(options.schema.id);
}
class Wrapper extends Component { class Wrapper extends Component {
render() { render() {
return createElement(Comp, { ...this.props, ref: this.props.forwardRef }); return createElement(Comp, { ...this.props, ref: this.props.forwardRef });
@ -63,10 +75,14 @@ export function compWrapper(Comp: any, options: { baseRenderer: IBaseRendererIns
patchDidCatch(Wrapper, options); patchDidCatch(Wrapper, options);
return cloneEnumerableProperty( const WrapperComponent = cloneEnumerableProperty(
forwardRef((props: any, ref: any) => { forwardRef((props: any, ref: any) => {
return createElement(Wrapper, { ...props, forwardRef: ref }); return createElement(Wrapper, { ...props, forwardRef: ref });
}), }),
Comp, Comp,
); );
cache.set(options.schema.id, WrapperComponent);
return WrapperComponent;
} }

View File

@ -615,7 +615,7 @@ export default function baseRendererFactory(): IBaseRenderComponent {
}); });
}); });
Comp = compWrapper(Comp, { baseRenderer: this }); Comp = compWrapper(Comp, { baseRenderer: this, schema });
components[schema.componentName] = Comp; components[schema.componentName] = Comp;
otherProps.ref = (ref: any) => { otherProps.ref = (ref: any) => {