react-activation实现缓存,且部分页面刷新缓存,清除缓存

1.安装依赖

javascript 复制代码
npm i -S react-activation

2.使用AliveScope 包裹根组件

javascript 复制代码
import { AliveScope } from "react-activation"
<AliveScope>
   <Router>
       <Switch>
           <Route exact path="/" render={() => <Redirect to="/login" push />} />        
           <Route path="/login" component={Login} />
           <Route path="/aaaa" component={App} />
           <Route path="/404" component={NotFound} />
           <Route component={NotFound} />
       </Switch>
   </Router>
</AliveScope>

3.缓存组价或者路由

缓存组件

javascript 复制代码
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>
}

缓存路由

javascript 复制代码
import KeepAlive from 'react-activation'
//name属性,是为了刷新时候,判断路由
<KeepAlive name={this.props.path}>
	<Route  path={path} exact={exact}  strict={strict}  render={(props)=>( <Component {...props} /> )} />
</KeepAlive>

4.keepAlive属性

属性名 属性 备注
when Boolean、Array、Function Boolean (true-卸载时缓存 false-卸载时不缓存) Array (第 1 位参数表示是否需要在卸载时 第 2 位参数表示是否卸载 的所有缓存内容,包括 中嵌的 ) Function (返回值为上述 Boolean 或 Array)
saveScrollPosition Boolean 自动保存滚动位置(默认true)
name string 缓存标识

5.在组件中手动刷新缓存,清除缓存

类组件

javascript 复制代码
import { withAliveScope } from 'react-activation'

class roleSetting extends Component {
	//组件内容
	//在路由跳转之前,将要跳转的二级页面缓存清空,解决从列表页跳转详情时,只有第一次掉接口,其他情况均不掉接口问题
	this.props.refreshScope('bbb')
	this.props.history.push({ pathname: "bbb", state: state});
	
	//清除所有缓存
	this.props.clear();
}
export default withAliveScope(roleSetting )

函数组件

javascript 复制代码
import { useAliveController } from 'react-activation'
const TeamList = (props) => {
	const { refreshScope, clear } = useAliveController()
	//在路由跳转之前,将要跳转的二级页面缓存清空,解决从列表页跳转详情时,只有第一次掉接口,其他情况均不掉接口问题
	refreshScope('aaa')
	props.history.push({
       pathname: 'aaa',
        state: state,
    });

	//清除所有缓存,比如退出登录时候
	clear();
}
export default TeamList

drop(name) 卸载缓存,不包括嵌套的KeepAlive

dropScope(name) 卸载缓存,包括嵌套的所有KeepAlive

refresh(name) 刷新缓存状态,不包括嵌套的KeepAlive

refreshScope(name) 刷新缓存状态,包括嵌套的所有KeepAlive

clear() 清空所有缓存

getCachingNodes() 获取所有缓存中的节点

相关推荐
The_era_achievs_hero1 天前
Echarts
前端·javascript·echarts
optimistic_chen1 天前
【Redis 系列】深入理解Redis核心特性:全局命令、内部编码与单线程架构
数据库·redis·缓存·redis命令·xsheel·内部编码
y***n6141 天前
Redis设置密码
数据库·redis·缓存
涔溪1 天前
Vite 和 Webpack 这两款主流前端构建工具的核心区别,包括它们的设计理念、工作机制和实际使用体验上的差异。
前端·webpack·vite
0思必得01 天前
[Web自动化] 开发者工具元素(Elements)面板
运维·前端·自动化·web自动化·开发者工具
遇到困难睡大觉哈哈1 天前
Harmony os ——ArkTS 语言笔记(五):泛型、空安全与可选链
前端·笔记·安全·harmonyos·鸿蒙
八哥程序员1 天前
你真的理解了 javascript 中的原型及原型链?
前端·javascript
冴羽1 天前
10 个 Nano Banana Pro 专业级生图技巧
前端·人工智能·aigc
7ayl1 天前
Vue3 - runtime-core的渲染器初始化流程
前端·vue.js
前端老宋Running1 天前
React 的“时光胶囊”:useRef 才是那个打破“闭包陷阱”的救世主
前端·react.js·设计模式