react路由缓存和多组件路由缓存demo

905 阅读2分钟

路由缓存演示:

切换社区路由, 在输入框写入Community

image.png

切换商城路由, 在输入框写入Shop

image.png

切回社区组件, 输入框的值依然在

image.png

多组件缓存演示.

假设社区有多篇文章, 我点击"文章1"链接查看详情, 点击"文章2"的时候, 生成"文章2"组件, 保留"文章1"内容, 下面是演示:

image.png

当我们回"文章1"链接的时候, 输入框的值仍能被缓存下来;

下面说一下实现的方法:

不想看方法的可以直接拉取项目运行(如果有帮助麻烦点一下星星,谢谢):gitee.com/chenZiHuang…

功能使用了插件: react-activation github.com/CJY0208/rea…

  1. 在入口文件引入

image.png

  1. routes路由配置使用CzhKeepAlive包裹, 如果需要多组件缓存的, 第三个参数传true

image.png

  1. 新建CzhRoutes路由文件,使用了 和 来做路由, 递归遍历第2步的路由配置生成路由组件, 在组件中引入模拟实现路由钩子

image.png

  1. 在App.js中引入CzhRoutes

image.png

关于 CzhKeepAlive 的实现:

import React from "react";
import KeepAlive from 'react-activation';
import { inject, observer } from 'mobx-react'
import { useLocation } from "react-router-dom";

class App extends React.PureComponent {
  constructor (props) {
    super(props)
  }
  render () {
    // 组件赋值
    let Component = this.props.component;
    return (
      // 如果是多组件缓存, 则使用 MultipleComponent
      this.props.isMultiple ? (
        <MultipleComponent com={Component} uniqueId={this.props.uniqueId}></MultipleComponent>
      ) : (
        // 单路由缓存
        <KeepAlive cacheKey={this.props.uniqueId}>
            <Component></Component>
        </KeepAlive>
      )
    )
  }
};

// 多组件缓存, 遍历存在mobx中的 pathCaches, 取出 uniqueId 对应的数组, 遍历生成多组件, 判断只有当页面fullPath等于当前组件fullPath的时候才展示
function _MultipleComponent({ routeCache, com, uniqueId }) {
  const Com = com;
  const location = useLocation();
  const fullPath = location.pathname + location.search;
  return (
    <div>
      {
        routeCache.pathCaches[uniqueId]?.map((option) => {
          return (
            fullPath === option.path ? (
              <KeepAlive cacheKey={option.path} key={option.path}>
                <Com></Com>
              </KeepAlive>
            ) : null
          )
        })
      }
    </div>
  )
};
const MemoComponent = React.memo(App);

// 注入mobx变量
const MultipleComponent = inject('routeCache')(observer(_MultipleComponent));

/**
 * 
 * @param {Element} component react组件
 * @param {String} uniqueId 组件唯一标识
 * @param {Boolean} isMultiple 是否多组件缓存
 * @returns 
 */
export default function CzhKeepAlive (component, uniqueId, isMultiple) {
  return <MemoComponent component={component} uniqueId={uniqueId} isMultiple={isMultiple}></MemoComponent>
}

有问题可以留言, 大家一起交流.