yarn add react-activation
config/config.js
配置 babel
babel: {
plugins: [
// ...
'react-activation/babel'
];
}
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')!);
src/router.tsx
包裹AliveScope
组件
import { AliveScope } from 'react-activation';
// ...
const router = createHashRouter(
createRoutesFromElements(
<Route
path="*"
element={
<AliveScope>
<AnimatedRoutes routes={transformCustomRoutes(routes)} />
</AliveScope>
}
/>
)
);
// ...
- 在需要保持状态的组件中使用
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;
}
});
- 当前缓存页面 useActivate 会执行多次 - 由 React.StrictMode 影响。查阅 严格模式
- 用 KeepAlive 包裹的组件中,react-router-dom 无法获取 params
- 如果区分
登录
/未登录
场景,需要在退出登录
或登录时
,清除缓存页面。 - 如非必要,尽量不用。