Skip to content

Latest commit

 

History

History
107 lines (77 loc) · 2.21 KB

File metadata and controls

107 lines (77 loc) · 2.21 KB

keep-alive

参考 react-activation

安装依赖

yarn add react-activation

使用步骤

  1. config/config.js 配置 babel
babel: {
  plugins: [
    // ...
    'react-activation/babel'
  ];
}
  1. src/index.tsx 改用 render 方法

react-activation NOTICE: (React v18+) DO NOT use ReactDOMClient.createRoot, use ReactDOM.render instead,

- import ReactDOM from 'react-dom/client';
+ import ReactDOM from 'react-dom';

// ...

-const root = ReactDOM.createRoot(document.getElementById('root')!);
-root.render(<App />);
+ReactDOM.render(<App />, document.getElementById('root')!);
  1. src/router.tsx 包裹 AliveScope 组件
import { AliveScope } from 'react-activation';
// ...

const router = createHashRouter(
  createRoutesFromElements(
    <Route
      path="*"
      element={
        <AliveScope>
          <AnimatedRoutes routes={transformCustomRoutes(routes)} />
        </AliveScope>
      }
    />
  )
);
// ...
  1. 在需要保持状态的组件中使用 KeepAlive

src/pages/repos/Detail.tsx

import KeepAlive from 'react-activation';

// ...

const WrapperDetailPage = (props: any) => {
  const { name } = useParams();

  return (
    <KeepAlive name="detail" id={name}>
      <DetailPage {...props} />
    </KeepAlive>
  );
};

export default WrapperDetailPage;

同时也要在 src/components/AsyncComponent 增加页面激活时设置标题

import { useActivate } from 'react-activation';

// ...

useActivate(() => {
  if (title) {
    document.title = title;
  }
});

常见问题

注意事项

  • 如果区分 登录/未登录 场景,需要在退出登录登录时,清除缓存页面。
  • 如非必要,尽量不用。