1.0.0-alpha.1 • Published 1 year ago

cache-react-router-alpha v1.0.0-alpha.1

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

目录

介绍

基础介绍

本组件是基于react框架 版本为18+react-router v5开发的基于react的缓存组件。使用方式如我们熟知的Vue框架中的keep-alive标签,将vue-router路由包裹起来,从而达到路由缓存的效果。

同时项目使用react新api react-hooks,使用useReducer用于状态存储,使开发更灵活,优化性能

技术框架介绍

需要以下知识点,就可以理顺该组件了 1 react-router v4+ 版本 官网:http://react-guide.github.io/react-router-cn/docs/guides/basics/RouteConfiguration.html 重点: 1.react-router //核心,公用的代码,重点看 2.react-router-config //用于路由配置 3.react-router-dom //浏览器环境路由,例如Link 4.react-router-native // react native路由(可以不用关注)

2 react v18+ 官网:https://react.docschina.org 1.需要掌握hooks相关 3.需要了解fiber结构与原理

能做什么

1 缓存页面信息,如页面切换后保存表单 2 保存页面滚动信息 3 提供缓存组件激活的监听器 4 清除缓存的方法

关于未来的想法

1 提供路由的生命周期,用于监听页面的状态,可以灵活的操控页面 2 父子页面可缓存,非父子页面可不缓存

使用

安装

注意:node版本需要在v10以上

npm install cache-react-router-alpha

快速使用

const { CacheSwitch, CacheRoute, useCacheDispatch, addKeeperListener } from 'cache-react-router-alpha';

CacheSwitch --对应原来的,基本用法,主要职责是找出匹配的route,也是为了让缓存的作用域只有一个 CacheRoute --对应原来的,包括要缓存的路由,如果不被它包裹,那么走的就是普通的路由逻辑 useCacheDispatch --用来清除缓存 addKeeperListener --监听器,当前是哪个页面,什么状态

示例

正常使用

正常的使用是这样的:Switch不一定是必须的,可以直接Route

   <Router history={history}>
        <Switch>
          <Route exact path="/" component={Login}/>
          <Route path="/home" component={Home}/>
        </Switch>
      </Router>
// 如果我们去掉switch组件的话,直接写route组件,这个页面也会正常渲染的,但是容易出现bug如果匹配到两个相同的路由他就会讲两个相同的路由显示到页面上,而不是只显示匹配到的第一个路由。
     <Router history={history}>
        <Route exact path="/" component={Login}/>
        <Route path="/home" component={Home}/>
    </Router>

要缓存的话就这么使用

function App() {
  return (
    <Router>
      <CacheSwitch>
        <Route path="/list" component={List}  />
        <CacheRoute path="/home" component={List2} scroll/> {/** 需要缓存就加 scroll */}
        <CacheRoute path="/page" component={Detail}/>
      </CacheSwitch>
    </Router>
  )
}

如果结构很复杂

withoutRoute:react-router的三个对象history, location, match塞进非router的组件中

function App() {
  return (
    <Router>
      <CacheSwitch withoutRoute>
        <div>
            <Route path="/list" component={List}  />
            <CacheRoute path="/home" component={List2} scroll/> {/** 需要缓存就加 scroll */}
        </div>
        <CacheRoute path="/page" component={Detail}/>
      </CacheSwitch>
    </Router>
  )
}

缓存组件监听器

可以使用:

const { addKeeperListener } from 'cache-react-router-alpha';

// 但是要辛苦一下在构造函数中监听

缓存中可能会存在的问题

1 页面存在轮询怎么办,页面切出去没有清空定时器的话,可能造成内存溢出 --答:目前的方式就是使用addKeeperListener,如在构造函数中使用

````jsx
constructor(prop){
    this.vlidateTimer = '';
    addKeeperListener((history,cacheKey)=>{
        const {cacheState} = history;
        if (cacheKey !== '/detail') {
            if (this.vlidateTimer) clearInterval(this.vlidateTimer)
        }
        if (cacheKey === '/detail' && cacheState.lastState === 'unActive') {
          //  this.excuteThing();
        }
    })
}
````