@rc-essential/keep-alive
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

react-keep-alive

基于react18模拟vue的keep-alive组件,实现页面/组件的状态保存

安装

pnpm add @rc-essential/keep-alive

使用

基于react-router-dom路由页面缓存

import '@rc-essential/keep-alive/dist/style.css'
import { KeepProvider, KeepAlive } from '@rc-essential/keep-alive'
import { useLocation, useOutlet } from 'react-router-dom'

const BasicLayoutWidthCache = () => {
  const outlet = useOutlet()
  const location = useLocation()
  
  /**
   * 用于区分不同页面以进行缓存
   */
  const cacheKey = useMemo(() => {
    return location.pathname + location.search
  }, [location])

  return (
    <div>
      <KeepAlive activeName={cacheKey}>{outlet}</KeepAlive>
    </div>
  )
}

useActivated/useDeactivated

useActivated: 用于监听被KeepAlive包装的组件的激活状态。 useDeactivated: 用于监听被KeepAlive包装的组件的失活状态。

  import { useActivated } from '@rc-essential/keep-alive'
    /**
     * 用于区分不同页面以进行缓存
     */
    const cacheKey = useMemo(() => {
      return location.pathname + location.search;
    }, [location])
  useActivated(cacheKey, () => {
    console.log('useActivated', cacheKey);
  })

/@rc-essential/keep-alive/

    Package Sidebar

    Install

    npm i @rc-essential/keep-alive

    Weekly Downloads

    0

    Version

    1.0.6

    License

    MIT

    Unpacked Size

    220 kB

    Total Files

    27

    Last publish

    Collaborators

    • wenzhen1