1、安装依赖

npm i -S react-activation

2、包裹根组件

import { AliveScope } from "react-activation"

<AliveScope>
	<App />
</AliveScope>

3、缓存组件

import { KeepAlive } from "react-activation"

export default () => {
  const [isShow, setIsShow] = useState(true)

  return <div>

    <button onClick={() => setIsShow(!isShow)}>切换</button>

    {
      isShow &&
      <KeepAlive>
        <Page3 />
      </KeepAlive>
    }
    <Page4 />
  </div>
}

4、路由缓存

<Route
  path="/page1"
  render={props => (
    <KeepAlive name="/page1">
      <Item {...props} />
    </KeepAlive>
  )}
/>

5、KeepAlive属性

属性名类型备注
whenBoolean、Array、FunctionBoolean (true-卸载时缓存 false-卸载时不缓存)
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐