react实现keep-alive

在项目中会遇到这样一个场景 上拉了N页的时候点进详情然后再返回列表,列表会重置,这里就需要对页面进行缓存,类似vue的keep-alive。
网上找了很多方案,可能demo是可以的,但是在复杂的场景下会有很多问题,基本上不能实现,经过一上午的折腾总算是弄出来了,采用的方案是 react-router-cache-route@1.8.4

代码如下

import React from "react";
import { HashRouter, Route } from "react-router-dom";
import CacheRoute, { CacheSwitch } from "react-router-cache-route";
import Home from "../views/list/index";
import Detail from "../views/detail/index";

const BasicRoute = () => (
  <HashRouter>
    <CacheSwitch>
      <CacheRoute
        exact
        path="/"
        component={Home}
        className="custom-style"
        saveScrollPosition={true}
        behavior={(cached) =>
          cached
            ? {
                style: {
                  position: "absolute",
                  zIndex: -9999,
                  opacity: 0,
                  visibility: "hidden",
                  pointerEvents: "none",
                  left: "-100%",
                },
                className: "__CacheRoute__wrapper__cached",
              }
            : {
                className: "__CacheRoute__wrapper__uncached",
              }
        }
      />
      <Route exact path="/detail/:id" component={Detail} />
      <Route render={() => <div>404 未找到页面</div>} />
    </CacheSwitch>
  </HashRouter>
);

export default BasicRoute;

这个方法有问题需要注意,上线的时候package.json需要锁定react-router-dom和react-router-cache-route,如果没有做就过段时间就会哭了。例子如下

 	"react-router-dom": "5.1.2",
    "react-router-cache-route": "1.8.4"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值