irychen / keepalive-for-react

React KeepAlive is a component that can cache the state of the component and reuse it when needed.
MIT License
162 stars 32 forks source link

使用KeepAlive组件包裹<Outlet/>时缓存不生效 #7

Closed yibird closed 4 months ago

yibird commented 4 months ago

使用useOutlet()是正常的,但是使用KeepAlive组件包裹时不生效,例如:

<KeepAlive activeName={cacheKey} max={10} strategy={'LRU'}>

irychen commented 4 months ago
import {useLocation, useOutlet} from 'react-router-dom';

function BasicLayoutWithCache() {

  // 这里第一层outlet必须使用  useOutlet
  const outlet = useOutlet();
  const location = useLocation();

  /**
   * to distinguish different pages to cache
   */
  const cacheKey = useMemo(() => {
    return location.pathname + location.search;
  }, [location]);

  return <div>
    <KeepAlive activeName={cacheKey} max={10} strategy={'LRU'}>
      {outlet}
    </KeepAlive>
  </div>
}