1、背景
当前框架使用的路由规则是使用React.lazy动态绘制的,使用KeepAlive组件缓存时一直不能缓存
export const RouteWithChildrenSubRoutes = (route: RouteProps & RrefetchRoute) => {
const LazyCompoent = React.lazy(() => import(`@pages/${addWebpackAliasPath(route.component)}`))
return (
<React.Suspense fallback={
route.loading === false
? <div></div>
: <div>{
route.loading === true
? 'loading...'
: route.loading
}</div>
}>
<LazyCompoent/>
</React.Suspense>
)
};
const KeepAliveRouter = ({router, loading, isVite, keepAlive}: SingleRouterProps) => {
return (
<AliveScope>
<KeepAlive when={keepAlive === 'auto' ? !router?.hideInMenu : true} id={`${router?.path}`}>
<RouteWithChildrenSubRoutes {...router} loading={loading} isVite={isVite}/>
</KeepAlive>
</AliveScope>
)
}
排查过程
初步怀疑是不支持异步组件,查看文档发现该问题已经支持链接
接着搜索isseus查到79,函数组件下一次渲染的时候必须跟缓存起来的组件必须是一个构造函数才行。
解决思路
将需要缓存的函数组件,同时缓存起来,下一次加载时使用缓存的函数。
export const RouteWithChildrenSubRoutes = (route: RouteProps & RrefetchRoute) => {
const _path = route?.path as string;
if (!PrefetchLazyComponent.get(_path)) {
PrefetchLazyComponent.add(_path, React.lazy(() => route.prefetchComponent || import(`@pages/${addWebpackAliasPath(autoComponents(route))}`)));
}
const LazyComponent = PrefetchLazyComponent.get(_path);
return (
<React.Suspense
fallback={
!route.loading
? null
: <div>
{
route.loading === true
? 'loading...'
: route.loading
}
</div>
}>
<LazyComponent/>
</React.Suspense>
)
};