一、基于react-route6
useOutlet
实现
二、代码呈现
import React, { useRef, createContext, useContext } from 'react'
import { useOutlet, useLocation, matchPath } from 'react-router-dom'
import type { FC } from 'react'
//在组件外部建立一个Context
export const KeepAliveContext = createContext<KeepAliveLayoutProps>({ keepalive: [], keepElements: {} })
//给予页面缓存设置条件判断
const isKeepPath = (aliveList: any[], path: string) => {let isKeep = falsealiveList.map(item => {if (item === path) {isKeep = true}if (item instanceof RegExp && item.test(path)) {isKeep = true} })return isKeep
}
//判断当前页面是否已缓存,是则控制hidden开关显示 ,不是则正常渲染
export function useKeepOutlets() {const location = useLocation()const element = useOutlet()const { keepElements, keepalive } = useContext<any>(KeepAliveContext)const isKeep = isKe