前言:React18实现keepalive效果 react-router-dom@6 outlet 路由页面缓存
注意是实现路由页面的缓存,其他的看官方文档自己摸索,原理都是一样的

1.版本环境

1
2
3
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2"

按道理版本低一点也没有什么关系。

2.react-activation

这是一个npm包,在react keep alive中用的人数应该是最多的包.
这是GitHub地址react-activation

2.1.安装

1
2
3
yarn add react-activation
# 或者
npm install react-activation

2.2.关闭严格模式

在main.tsx里把<React.StrictMode></React.StrictMode>这个标签删掉。

2.3.AliveScope使用

一般把AliveScope放在App外层,但是要在Router内层。
在这里插入图片描述

2.4.KeepAlive使用

在路由表里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import Login from "../pages/Login";
import Main from "../pages/Main";
import Query from "../pages/Main/Query";
import Index from "../pages/Main/Index/index";
//如果懒加载的话第一次点击不能渲染出组件,要缓存的路由不能懒加载!!
// const Query = lazy(() => import("../pages/Main/Query"))
import KeepAlive from 'react-activation'
const routes: RouteObject[] = [
{
path: '/main',
element: <Main />,
children: [
{
path: "index",
//KeepAlive一定一定要加id!!!
element:<KeepAlive id="index" ><Index /></KeepAlive>
},
{
path: "query",
element: <KeepAlive id="query"><Query /></KeepAlive>
},
]
},
{
path: '/login',
element: <Login />
}
]

KeepAlive标签一定一定要加id!!!
要缓存的路由不能懒加载!!!

2.5.Outlet放置

正常放就行,该放哪就放哪。我这个就是放在Main组件里,因为我的<Index />和<Query />两个子路由都是属于<Main />的。
在这里插入图片描述

3.结束