react 页面缓存插件react-router-cache-route

功能

此插件可以满足缓存上一页的功能,即:返回上一页的时候,上一页的滚动条、动作状态等等和离开这个页面时的状态保持一致。

简介

搭配 react-router 工作的、带缓存功能的路由组件,类似于 Vue 中的 keep-alive 功能。

原理

Route 中配置的组件在路径不匹配时会被卸载(render 方法中 return null),对应的真实节点也将从 dom 树中删除,利用Route暴露的children方法,让我们手动控制渲染。

安装

注意:作者测试使用时版本为1.4.6

npm install react-router-cache-route --save

注意事项

缓存语句不要写在 Switch 组件当中,因为 Switch组件会卸载掉所有非匹配状态下的路由,需使用 CacheSwitch 替代 Switch。

使用 when 属性决定何时使用缓存功能,可选值为 [forward, back, always] ,默认值为 forward。

使用 className 属性给包裹组件添加自定义样式。

也可以使用 behavior 属性来自定义缓存状态下组件的隐藏方式,工作方式是根据 CacheRoute 当前的缓存状态,返回一个作用于包裹组件的 props。

代码示例

路由改写

import React from 'react'
import { HashRouter as Router, Switch, Route } from 'react-router-dom'
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'

import List from './components/List'
import Item from './components/Item'

import List2 from './components/List2'
import Item2 from './components/Item2'

const App = () => (
  
    {/*
      也可使用 render, children prop
       } />
      或
      
        {props => }
      
        
支持多个子组件
*/} (cached ? { style: { position: 'absolute', zIndex: -9999, opacity: 0, visibility: 'hidden', pointerEvents: 'none' }, className: '__CacheRoute__wrapper__cached' } : { className: '__CacheRoute__wrapper__uncached' })} /> (
404 未找到页面
)} />
) export default App

额外的生命周期

使用 CacheRoute 的组件将会得到一个名为 cacheLifecycles 的属性,里面包含两个额外生命周期的注入函数 didCache 和 didRecover,分别用在组件 被缓存 和 被恢复 时

import React, { Component } from 'react'

export default class List extends Component {
  constructor(props, ...args) {
    super(props, ...args)
    props.cacheLifecycles.didCache(this.componentDidCache)
    props.cacheLifecycles.didRecover(this.componentDidRecover)
  }
  
  componentDidCache = () => {
    console.log('List cached')
  }

  componentDidRecover = () => {
    console.log('List recovered')
  }

  render() {
    return (
      // ...
    )
  }
}

github地址

你可能感兴趣的:(react 页面缓存插件react-router-cache-route)