import { useLocation, KeepAlive, history } from 'umi';
import { PageLoading, PageContainer } from '@ant-design/pro-layout';
export default function SwitchTabsLayout(props: RouteTabsLayoutProps): JSX.Element {
// const {clear} = useAliveController()
const { mode, loading, routes, children, ...rest } = props;
const location = useLocation() as H.Location;
const originalTabsRoutes = memoizedOneLocaleRoutes(routes!);
if (mode && isSwitchTab(location as any, originalTabsRoutes)) {
if (routes) {
return (
<SwitchTabs
mode={mode}
{...rest}
originalRoutes={originalTabsRoutes} // animated={false}
>
<PageContainer>
<KeepAlive
saveScrollPosition="screen" //自动保存共享屏幕容器的滚动位置
id={history.location.search || history.location.pathname} // 根据参数去缓存,如果参数不同就缓存多份,如果参数相同就使用同一个缓存。这样解决了传参改变时,页面不刷新的问题
when={() => { // 根据路由的前进和后退状态去判断页面是否需要缓存,前进时缓存,后退时不缓存(卸载)。 when中的代码是在页面离开(卸载)时触发的
return history.action != 'POP'; //true卸载时缓存,false卸载时不缓存
}}
>
{children}
</KeepAlive>
</PageContainer>
</SwitchTabs>
);
}
}
return children;
}
···
![在这里插入图片描述](https://img-blog.csdnimg.cn/57617e7883cd4d98a9909573b97b2888.png)
react 使用Keep-alive 缓存页面数据
最新推荐文章于 2024-03-06 12:54:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)