react Activation路由缓存的理解

1,413 阅读2分钟

主要组件

1、KeepALive

要缓存的内容,该组件用于包裹要缓存的组件,该组件需要一个唯一缓存id标识,可以借用babel添加react-activation/babel的plugins生成,否则只能在组件中添加cacheKey属性:

<KeepAlive cacheKey="UNIQUE_ID" />

2、AliveScope

存储组件,该组件用于储存各个KeepAlive组件。原理上是将 <KeepAlive /> 的 children 属性传递到 <AliveScope /> 中, <AliveScope />通过自己的 <Keeper /> 进行渲染 <Keeper /> 完成渲染后通过 DOM 操作,将内容转移到 <KeepAlive /> 中,由于 <Keeper /> 不会被卸载,故能实现缓存功能。 所以AliveScope组件需要放在不会被销毁的位置。

注意:与 react-router 或 react-redux 配合使用时,建议将 <AliveScope> 放置在 <Router> 或 <Provider> 内部

生命周期和hooks

1、ClassComponent

ClassComponent 可配合 withActivation 装饰器,其中生命周期componentDidActivate 与 componentWillUnactivate 对应激活与缓存两种状态

2、FunctionComponent

FunctionComponent 则分别使用 useActivate 与 useUnactivate hooks 钩子

缓存控制

1、手动控制

1)、先给需要控制的<KeepAlive /> 标签增加 name 属性

2)、Hooks使用useAliveController进行控制,该hooks返回以下属性:

  • drop(name) :卸载目标缓存节点,多层缓存仅卸载第一层内容;
  • dropScope(name) :卸载目标缓存节点,卸载所有内容;
  • refresh(name) :刷新目标缓存节点,多层缓存仅刷新第一层内容;
  • refreshScope(name) :刷新目标缓存节点,多层缓存仅刷新第一层内容;
  • clear() :清空所有缓存节点;
  • getCachingNodes() :获取所有缓存节点。

2、自动控制

<KeepAlive />组件中添加when属性用于控制:

  • whenBoolean:true卸载时缓存,false卸载时不缓存;
  • when 为 Array:第一位表示是否卸载时候缓存,第二位表示是否卸载里面所有内容;
  • when 为 Function:可返回BooleanArray

3、多份缓存

循环里或者同一位置,默认会使用同一份缓存,可在<KeepAlive />组件加入id来分成多分缓存, 如:

<Route
  path="/item/:id"
  render={props => (
    <KeepAlive>
      <Item {...props} />
    </KeepAlive>
  )}
/>

4、保持滚动位置(saveScrollPosition默认为true)

saveScrollPosition可为Boolean'screen'

  • Boolean,表示是否保持滚动状态;
  • 'screen',表示自动保存屏幕容器滚动位置。

参考

React Activation中文文档