@@ -5,9 +5,11 @@ import { REPORT_NAME, RuntimeConfig } from '@alipay/alex-core';
55import { createApp } from './createApp' ;
66import { Root } from '../core/Root' ;
77import { RootProps , LandingProps } from '../core/types' ;
8- import { useConstant } from '../core/hooks' ;
8+ import { setSingleInjector , singleInjector , useConstant } from '../core/hooks' ;
99import { IConfig , IAppInstance } from './types' ;
1010import styles from '../core/style.module.less' ;
11+ import { setInjector } from '@opensumi/di/dist/helper' ;
12+ import { Injector } from '@opensumi/di' ;
1113
1214export interface IAppRendererProps extends IConfig {
1315 onLoad ?( app : IAppInstance ) : void ;
@@ -119,3 +121,69 @@ export const AppRenderer: React.FC<IAppRendererProps> = ({ onLoad, Landing, ...o
119121 </ Root >
120122 ) ;
121123} ;
124+
125+ // 缓存apprender 每次渲染都不卸载组件
126+ export const AppRenderer2 : React . FC < IAppRendererProps > = ( { onLoad, Landing, ...opts } ) => {
127+
128+ const app = useConstant ( ( ) => createApp ( {
129+ ...opts ,
130+ // @ts -ignore
131+ injector : singleInjector
132+ } ) ) ;
133+ const themeType = useConstant ( ( ) => app . currentThemeType ) ;
134+ const appElementRef = useRef < React . ReactElement | null > ( null ) ;
135+ setSingleInjector ( app . injector )
136+
137+ console . log ( 'app' , app ) ;
138+ // 确保回调始终为最新
139+ // TODO: 用 PropsService
140+ const runtimeConfig : RuntimeConfig = app . injector . get ( RuntimeConfig ) ;
141+ runtimeConfig . workspace = opts . runtimeConfig . workspace ;
142+
143+ const [ state , setState ] = useState < {
144+ status : RootProps [ 'status' ] ;
145+ error ?: RootProps [ 'error' ] ;
146+ } > ( ( ) => ( { status : 'loading' } ) ) ;
147+
148+ useEffect ( ( ) => {
149+ app
150+ . start ( ( appElement ) => {
151+ appElementRef . current = appElement ;
152+ setState ( { status : 'success' } ) ;
153+ return Promise . resolve ( ) ;
154+ } )
155+ . then ( ( ) => {
156+ onLoad ?.( app ) ;
157+ } )
158+ . catch ( ( err : Error ) => {
159+ setState ( { error : err ?. message || localize ( 'error.unknown' ) , status : 'error' } ) ;
160+
161+ ( app . injector . get ( IReporterService ) as IReporterService ) . point (
162+ REPORT_NAME . ALEX_APP_START_ERROR ,
163+ err ?. message ,
164+ {
165+ error : err ,
166+ }
167+ ) ;
168+ getDebugLogger ( ) . error ( err ) ;
169+ setTimeout ( ( ) => {
170+ throw err ;
171+ } ) ;
172+ } ) ;
173+
174+ return ( ) => {
175+ // app.destroy();
176+ } ;
177+ } , [ ] ) ;
178+
179+ const rootClassName = useMemo (
180+ ( ) => ( opts . runtimeConfig . hideEditorTab ? styles [ 'hide-editor-tab' ] : '' ) ,
181+ [ opts . runtimeConfig . hideEditorTab ]
182+ ) ;
183+
184+ return (
185+ < Root { ...state } theme = { themeType } Landing = { Landing } className = { rootClassName } >
186+ { appElementRef . current }
187+ </ Root >
188+ ) ;
189+ } ;
0 commit comments