react/umi实现KeepAlive

1,257 阅读1分钟

前言✨

此keepAlive并不是指TCP和HTTP的keepAlive,而是指vue所特有的内置API。

使用方法:<keep-alive>包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们,主要用于保留组件状态或避免重新渲染。

实际场景中经常会用到,比如:新闻页第二页点击进入详情,再返回回到第二页上一次停留的位置,这可以大幅度提升用户体验和减少接口请求次数从而提升性能。而且在vue中使用极其方便,但是react中却是没有直接内置,不过利用插件我们也能达到效果!

一、安装依赖🎈

react:

$ yarn add react-activation
// or
$ npm install react-activation

umi:(umi-plugin-keep-alive其实也是基于react-activation,只不过集成了,可以直接在umi导出)

$ npm install umi-plugin-keep-alive --save
// or
$ yarn add umi-plugin-keep-alive

二、基础使用和预览💻

这里我使用的是umi,就以umi来展示

import { KeepAlive } from 'umi';
import { useState } from 'react';
import { Button } from 'antd';
const Home = (props) => {
  const [show, setShow] = useState(true);
  const toggle = () => setShow((show) => !show);
  return (
    <>
      {show && (
        <KeepAlive name="Test">
          <Test />
        </KeepAlive>
      )}
      <Button onClick={toggle}>显示/隐藏</Button>
     </>
  );
};

function Test() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>count: {count}</p>
      <Button onClick={() => setCount((count) => count + 1)} type="primary">
        Add
      </Button>
    </div>
  );
}

ezgif.com-gif-maker.gif

三、注意事项👀

1.Breaking Change 由实现原理引发的额外问题

2.对 Context 的破坏性影响

3.对依赖于 React 层级的功能造成影响

以上问题官方都有特定的修复方式:github.com/CJY0208/rea…