kxd-react-route-cache
Version:
change color from react-route-cache for my project
73 lines (72 loc) • 2.77 kB
JavaScript
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', 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([]);
useEffect(() => {
var _a, _b;
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;
});
// 调用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));
}
});
}
const existTab = tabs.find((item) => item.key === key);
if (!existTab) {
setTabs([
...tabs,
{
key: key,
label: (_b = matches[matches.length - 1].handle) === null || _b === void 0 ? void 0 : _b[nameKey],
},
]);
}
}, [pathname, search, mode]);
return (React.createElement(KeepAliveContext.Provider, { value: {
activateds,
setActivateds,
deactivateds,
setDeactivateds,
active,
setActive,
tabs,
setTabs,
caches,
setCaches,
} }, children));
};
export const useKeepAliveContext = () => {
const context = useContext(KeepAliveContext);
if (!context) {
throw new Error('useKeepAlive必须在KeepAliveContext中使用');
}
return context;
};