UNPKG

react-route-cache

Version:
85 lines (84 loc) 3.17 kB
import React, { useContext, useState, createContext, useEffect } from 'react'; import { useLocation, useMatches } from 'react-router-dom'; const KeepAliveContext = createContext({ activateds: {}, deactivateds: {} }); KeepAliveContext.displayName = 'KeepAliveContext'; export const KeepAliveScope = ({ mode = 'path', nameKey = 'name', cacheMaxRemove, children, }) => { const { pathname, search } = useLocation(); const matches = useMatches(); const [activateds, setActivateds] = useState({}); const [deactivateds, setDeactivateds] = useState({}); const [active, setActive] = useState(''); const [tabs, setTabs] = useState([]); const [caches, setCaches] = useState([]); const dispatchActivateds = () => { var _a; const key = mode === 'path' ? pathname : pathname + search; // 调用activateds if ((_a = activateds[key]) === null || _a === void 0 ? void 0 : _a.length) { activateds[key].forEach((item) => { const deactivated = item(); if (deactivated) { deactivated.__shouldRemove = true; if (!deactivateds[key]) { deactivateds[key] = []; } deactivateds[key].push(deactivated); setDeactivateds(Object.assign({}, deactivateds)); } }); } }; useEffect(() => { var _a; const key = mode === 'path' ? pathname : pathname + search; // 调用deactivateds方法 setActive((active) => { var _a; if ((_a = deactivateds[active]) === null || _a === void 0 ? void 0 : _a.length) { deactivateds[active] = deactivateds[active].filter((item) => { item(); return !item.__shouldRemove; }); setDeactivateds(Object.assign({}, deactivateds)); } return key; }); dispatchActivateds(); const label = (_a = matches[matches.length - 1].handle) === null || _a === void 0 ? void 0 : _a[nameKey]; const existTab = tabs.find((item) => item.key === key); if (!existTab && label) { setTabs([ ...tabs, { key: key, label, }, ]); } }, [pathname, search, mode]); useEffect(() => { const key = mode === 'path' ? pathname : pathname + search; dispatchActivateds(); }, [activateds]); return (React.createElement(KeepAliveContext.Provider, { value: { activateds, setActivateds, deactivateds, setDeactivateds, active, setActive, tabs, setTabs, caches, setCaches, nameKey, cacheMaxRemove, } }, children)); }; export const useKeepAliveContext = () => { const context = useContext(KeepAliveContext); if (!context) { throw new Error('useKeepAlive必须在KeepAliveContext中使用'); } return context; };