react keep-aplive快速实现.(借助插件react-activation)

523 阅读1分钟

第一步:安装 react-activation

npm install react-activation

第二步:路由改造.核心代码

image.png


import KeepAlive from "react-activation";


const AssembleRoutes = () => {
  /** 默认路由 */
  const rawRoutes = [...] as DataRouteObject[];

  //!!! 包裹keepAlive ------------------------
  loadKeepAlive(rawRoutes);
  
  const AllRoutes = useRoutes(rawRoutes);
  return AllRoutes;
};
/** 为所有的路由项,包裹一层keepAlive,使之可以被缓存 */
const loadKeepAlive = (rawRoutes: DataRouteObject[]) => {
  for (let index = 0; index < rawRoutes.length; index++) {
    const route = rawRoutes[index];
    if (route.path && route.element) {
      route.element = <KeepAlive id={route.path}>{route.element}</KeepAlive>;
    }
    if (route?.children?.length > 0) {
      loadKeepAlive(route.children);
    }
  }
};

export const RootRouter = () => {
  return (
    <HashRouter>
      <AliveScope>
        <AssembleRoutes></AssembleRoutes>
      </AliveScope>
    </HashRouter>
  );
};

核心有两点:

1.使用<AliveScope>包裹所有routes.

2.使用<KeepAlive id={"id必需设置"}>包裹原route.element.

-- 完 --