- react路由缓存方法
# 使用
npm i react-activation
1
- 最外层路由下放一个
AliveScope
干预缓存路由import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import { BrowserRouter, } from 'react-router-dom'; import { AliveScope } from 'react-activation' ReactDOM.render( <BrowserRouter> <AliveScope> <App /> </AliveScope> </BrowserRouter> , document.getElementById('root'));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 - 需要缓存的文件用
KeepAlive
包裹import KeepAlive from 'react-activation' const routerMap = [ { path: "/home", element: <KeepAlive cacheKey="Home" ><Home /></KeepAlive>, }, { path: "/about", element: <KeepAlive cacheKey="About" ><About /></KeepAlive>, }, { path: "/detail", element: <Detail />, }, { path: "/", element: <Navigate to="/home" />, }, { path: '*', element: <Err /> } ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 - 使用
function App() { const elements = useRoutes(routerMap); return ( <div> {elements} </div> ) }
1
2
3
4
5
6
7
8