react实现keep-alive

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

代码如下

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 = () => (
  
    
      
          cached
            ? {
                style: {
                  position: "absolute",
                  zIndex: -9999,
                  opacity: 0,
                  visibility: "hidden",
                  pointerEvents: "none",
                  left: "-100%",
                },
                className: "__CacheRoute__wrapper__cached",
              }
            : {
                className: "__CacheRoute__wrapper__uncached",
              }
        }
      />
      
       
404 未找到页面
} />
); 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"

你可能感兴趣的:(react)