0.0.2 • Published 11 months ago

@bzlab/react-keep-alive v0.0.2

Weekly downloads
-
License
-
Repository
-
Last release
11 months ago

react-keep-alive

React缓存插件

描述

组件一共对外暴露了三个接口: 1. 用KeepAliveScope组件包裹整个应用 2. 用KeepAliveItem组件包裹你要缓存的组件给上缓存cacheId和Key,并且要唯一 3. 被KeepAlive组件包裹的组件会注入onActivate和onUnActivate生命周期钩子函数和cacheId 4. useCache可以操作组件缓存,里面包含getCache,getCaches,removeCache

快速上手

npm i @bzlab/react-keep-alive

首先用KeepAliveScope组件包裹应用,注意要被包裹在Router组件里面,否则路由hooks会用不了

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import { BrowserRouter } from 'react-router-dom'
import { KeepAliveScope } from '@bzlab/react-keep-alive'

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <BrowserRouter>
    <KeepAliveScope>
      <App />
    </KeepAliveScope>
  </BrowserRouter>
)
  • 使用react-router@5.x写法:
import { Route } from 'react-router-dom'
import { KeepAliveItem } from '@bzlab/react-keep-alive'

const cacheId = 'cacheId'
const Layout = () => {
  return (
    <Route path="/">
      <KeepAliveItem cacheId={cacheId} key={cacheId}>
          <Demo />
      </KeepAliveItem>
    </Route>
  )
}
export default Layout;
  • 使用react-router@6.x写法:

Demo组件演示被包裹的业务组件使用细节:

import { KeepAliveItem } from '@bzlab/react-keep-alive'
import { useCache } from '@bzlab/react-keep-alive'
import { KeepAliveComponentProps } from '@bzlab/react-keep-alive/es/components/keep-alive-item'

interface IProps {}
const Input = () => <input />
const cacheId = 'cacheId'
const Demo = ({ onActivate, onUnActivate, cacheId }: KeepAliveComponentProps<IProps>) => {
  const { getCache, getCaches, removeCache } = useCache() // 缓存hooks
  // 注册生命周期钩子函数
  useEffect(() => {
    onActivate!(() => console.log('组件激活了'), cacheId!)
    onUnActivate!(() => console.log('组件休眠了'), cacheId!)
  }, [])

  const [show, setShow] = useState(false)
  return (
    <>
      <h2>demo</h2>
      {show && (
        <KeepAliveItem key={cacheId} cacheId={cacheId}>
          <Input /> 
        </KeepAliveItem>
      )}
      <button onClick={() => console.log(getCache('cacheId'))}>当前缓存</button>
      <button onClick={() => console.log(getCaches())}>所有缓存</button>
      <button onClick={() => removeCache('cacheId')}>销毁缓存</button>
      <button onClick={() => setShow((prev) => !prev)}>
        {show ? '隐藏' : '显示'}
      </button>
    </>
  )
}

routes.tsx文件:

import { RouteObject } from 'react-router-dom'
import { KeepAliveItem } from '@bzlab/react-keep-alive'

const cacheId = 'cacheId'
const routes: RouteObject[] = [
  {
    path: '/demo',
    element: (
      <KeepAliveItem cacheId={cacheId} key={cacheId}>
        <Demo />
      </KeepAliveItem>
    ),
  }
]

export default routes

发布包

npm publish --registry https://registry.npmjs.org --access public                        

卸载包

npm unpublish @bzlab/react-keep-alive@0.0.1 --force --registry https://registry.npmjs.org
0.0.2

11 months ago

0.0.1

11 months ago