0.1.0 • Published 2 years ago
@lin-react/keepalive v0.1.0
react-keeplive缓存库
原理就是缓存dom,在组件挂载的时候将缓存的dom替换上。
用法
- 建议包裹页面级别组件,props的改变暂时无法触发页面的刷新。
- 滚动缓存还处于开发阶段,暂时只支持第一层的dom。
在入口包裹Provider
import { KeepAliveProvider } from '@lin-react/keepalive';
import App from './routes';
ReactDOM.createRoot(document.getElementById('root')!).render(
<KeepAliveProvider>
<App></App>
</KeepAliveProvider>
);
将需要缓存的组件,通过WithKeepLive
包裹起来,入
import { WithKeepLive } from '@lin-react/keepalive'
import Test from '@/Test';
const AliveTest = WithKeepLive(Test, { cacheId: '/test', scroll: true });
这样AliveTest就已经具有缓存性了。 WithKeepLive的参数
- 第一个是需要缓存的组件
- 第二个是options,主要有cacheId,组件的缓存ID,必传且唯一。还有scorll,表示是否要缓存滚动。
此外,通过props,向被WithKeepLive
包裹的组件注入一个unMount函数。用来清除缓存,只要调用unMount,组件会立马重新渲染并且重新刷新缓存。
const AliveUser = WithKeepLive(USER, { cacheId: '/user' });
const USER = (props: any) => {
return (
<div>
<button onClick={() => props.unMount('/home/son')}>重置Home</button>
</div>
);
};
最后,组件目前提供两个hooks,useActive
, useUnActive
。因为缓存dom的原因,故useEffect等生命周期不会被调用,为此,提供了两个Hooks替代生命周期。
useActive
会在组件激活的时候调用。
useUnActive
会在组件即将离开的时候调用。
import { useActive, useUnActive } from '@lin-react/keepalive'
const Son = ({ unMount }: any) => {
const [state, setState] = useState(1);
const stateRef = useRef(state)
useEffect(()=>{stateRef.current = state},[state])
useActive(() => {
console.log('组件即将渲染');
console.log(stateRef.current, fatherState);
setTimeout(()=>{unMount('/home/son')},2000)
}, '/home/son');
useUnActive(() => {
console.log('组件即将离开');
console.log(stateRef.current, fatherState);
}, '/home/son');
return (
<>
<div>
{state}
<button onClick={() => setState(state + 1)}>+</button>
</div>
</>
);
};
const AliveSon = WithKeepLive(Son, { cacheId: '/home/son' });
最后,目前缓存的组件无法通过props来刷新组件,也就是缓存的组件的props即使改变,也不会引起组件重新渲染。
0.1.0
2 years ago