UNPKG

react-route-cache

Version:
70 lines (69 loc) 3.29 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React from 'react'; import { useEffect, useRef } from 'react'; import { Component } from './component'; import { useKeepAliveContext } from '../context'; import { useMatches } from 'react-router-dom'; import { useKeepAlive } from '../hooks/use-keep-alive'; export const KeepAlive = (_a) => { var _b; var { children, exclude, include, max = 10, style, className, styles } = _a, rest = __rest(_a, ["children", "exclude", "include", "max", "style", "className", "styles"]); const containerRef = useRef(null); const { active, tabs, caches, setCaches, nameKey, cacheMaxRemove } = useKeepAliveContext(); const { close } = useKeepAlive(); const matches = useMatches(); // 必须要有name属性才可以缓存,cache设置为false才不缓存 const handle = matches[matches.length - 1].handle; const cache = (handle === null || handle === void 0 ? void 0 : handle[nameKey]) && ((_b = handle === null || handle === void 0 ? void 0 : handle.cache) !== null && _b !== void 0 ? _b : true); useEffect(() => { if (!active || !cache) { return; } let cacheList = caches; // 添加 const cacheRoute = cacheList.find((item) => item.name === active); if (!cacheRoute) { cacheList.push({ name: active, ele: children, }); // 缓存超过上限的 if (cacheList.length > max) { const remove = cacheList.shift(); console.log(remove); if (cacheMaxRemove) { close(remove === null || remove === void 0 ? void 0 : remove.name); } } } cacheList = cacheList.filter((item) => tabs.some((tab) => tab.key === item.name)); if (exclude || include) { cacheList = cacheList.filter(({ name }) => { if (exclude && exclude.includes(name)) { return false; } if (include) { return include.includes(name); } return true; }); } setCaches([...cacheList]); }, [children, active, exclude, max, include, tabs]); return (React.createElement(React.Fragment, null, cache && React.createElement("div", Object.assign({ ref: containerRef, style: Object.assign(Object.assign({}, style), styles === null || styles === void 0 ? void 0 : styles.wrapper), className: className }, rest)), !cache && children, caches.map(({ name, ele }) => { return (React.createElement(Component, { key: name, name: name, show: name === active, to: containerRef, style: styles === null || styles === void 0 ? void 0 : styles.content }, ele)); }))); };