react路由缓存插件react-activation
一开始去看了一下react-keep-alive,然后试了一下,发现在react-router-dom V6中已经不好使了,github上也看到有人遇到了同样的问题,就是不能触发点击事件,然后自己也去提了一下pr,仔细一看,作者已经好几年没维护了,应该也没有下文了。后面又去了解了一下另一个插件react-activation,github地址:github.com/CJY0208/rea…,发现挺简单的。
1.安装react-activation
npm i react-activation
2.使用
2.1配置
//如果你用的是官方脚手架搭建的react项目,并且运行了npm run test,那么就在configwe
文件夹下的jest文件夹的babelTransform.js里找到 babelrc,添加以下
babelrc: {
"plugins": [
"react-activation/babel"
]
},
//或者直接在使用KeepAlive的时候添加cacheKey,官方说是为了稳定性
<KeepAlive cacheKey="UNIQUE_ID" />
2.2用 <KeepAlive>
包裹需要保持状态的组件
//这里直接拿我写的比较完整的router配置来说明
import KeepAlive from 'react-activation' //引入
export default function Myrouter() {
const element = useRoutes([
{
path: '/film',
element: <KeepAlive cacheKey="UNIQUE_ID">
{LazyLoad('film')}
</KeepAlive> //包裹需要保持状态的组件
}
return element
}
const LazyLoad = (path) => {
return (
<React.Suspense fallback={<>...加载中</>}>
React.lazy(() => import(`../views/${path}`))
</React.Suspense>
)
}
2.3在router路由入口处
import {HashRouter} from 'react-router-dom';
import Myrouter from './router/index2.js';
import { AliveScope } from 'react-activation'//引入,需要结合使用
function App() {
return (
<HashRouter>
<AliveScope>
<Myrouter/>
</AliveScope>
</HashRouter>
);
}
export default App;