react-cache-router
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

react-cache-router

基于reactReactVersion实现的路由缓存功能

搭配react-router-domreactRouterVersion以上进行工作

安装

# 使用npm安装
npm install react-cache-router --save
# 或者使用yarn
yarn add react-cache-router

为何实现

在使用vue-router时,只要使用keep-alive组件包裹,便能将在路由发生改变时,将组件状态记录下来。

而在使用react-router时,发现react并没keep-alive组件,route也没有提供缓存组件状态的方法,导致每次路由回退时,当前路由下的数据和滚动位置丢失。

react-cache-router就是为了实现react-routerkeep-alive功能。

DEMO演示

实现原理

我们利用了react-router中,无论当前路由是否匹配,children永远不会被卸载的原理。

react-router源码

使用方法

提供了CacheSwitchCacheRoute,只要替换掉原本的react-router-dom提供的SwitchRoute即可使用。

CacheSwitchCacheRoute是互相依赖,没办法单独使用。

import * as React from 'react';
import {HashRouter} from 'react-router-dom';
import {CacheSwitch, CacheRoute} from 'react-cache-router';
import {Home} from "./pages/home";
import {Myself} from "./pages/myself"
 
export class App extends React.Component{
    render(){
        return <HashRouter>
            <CacheSwitch>
                <CacheRoute exact={true} path="/home" component={Home}/>
                <CacheRoute exact={true} path="/myself" component={Myself}/>
            </CacheSwitch>
        </HashRouter>;
    }
}

参数

CacheSwitch

参数名称 类型 默认值 具体描述
when "forward" "back" "all" "none" "forward" 表示何时才缓存路由,forward表示路由前进(PUSH or REPLACE)时缓存,back表示路由后退(POP)时缓存,all无论前进和后退均缓存(即不主动卸载缓存,但超出最大缓存路由数还是会卸载路由),none即不缓存。
maxRoutes Number -1 最多缓存几条路由,默认-1,即无缓存数量限制,超过数量后会优先卸载最后使用到的路由

CacheRoute

cacheRoute 继承Route的所有参数,并添加了以下的参数

参数名称 类型 默认值 具体描述
cache Boolean true 设置当前路由是否需要缓存,默认需要缓存。
local Boolean false 本地持久缓存,仅当cache为true时生效,不受CacheSwitch的maxRoutes和when为forward和back的影响。

Package Sidebar

Install

npm i react-cache-router

Weekly Downloads

40

Version

1.1.0

License

ISC

Unpacked Size

78.4 kB

Total Files

28

Last publish

Collaborators

  • wengyifan