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() 获取所有缓存中的节点

相关推荐
叶梅树9 分钟前
从零构建A股量化交易工具:基于Qlib的全栈系统指南
前端·后端·算法
巴博尔14 分钟前
uniapp的IOS中首次进入,无网络问题
前端·javascript·ios·uni-app
Achou.Wang33 分钟前
源码分析 golang bigcache 高性能无 GC 开销的缓存设计实现
开发语言·缓存·golang
Asthenia04121 小时前
技术复盘:从一次UAT环境CORS故障看配置冗余的危害与最佳实践
前端
csj501 小时前
前端基础之《React(1)—webpack简介》
前端·react
被巨款砸中1 小时前
前端 20 个零依赖浏览器原生 API 实战清单
前端·javascript·vue.js·web
文韬_武略1 小时前
web vue之状态管理Pinia
前端·javascript·vue.js
mosen8681 小时前
【Vue】Vue Router4x关于router-view,transtion,keepalive嵌套写法报错
前端·javascript·vue.js
蓝婴天使2 小时前
基于 React + Go + PostgreSQL + Redis 的管理系统开发框架
react.js·postgresql·golang
写不来代码的草莓熊2 小时前
vue前端面试题——记录一次面试当中遇到的题(5)
前端