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

相关推荐
你的人类朋友34 分钟前
说说git的变基
前端·git·后端
姑苏洛言37 分钟前
网页作品惊艳亮相!这个浪浪山小妖怪网站太治愈了!
前端
字节逆旅43 分钟前
nvm 安装pnpm的异常解决
前端·npm
Jerry1 小时前
Compose 从 View 系统迁移
前端
m0_595199851 小时前
Redis(以Django为例,含具体操作步骤)
数据库·redis·缓存
GIS之路1 小时前
2025年 两院院士 增选有效候选人名单公布
前端
四岁半儿1 小时前
vue,H5车牌弹框定制键盘包括新能源车牌
前端·vue.js
烛阴2 小时前
告别繁琐的类型注解:TypeScript 类型推断完全指南
前端·javascript·typescript
gnip2 小时前
工程项目中.env 文件原理
前端·javascript
JefferyXZF2 小时前
Next.js Server Actions 详解: 无缝衔接前后端的革命性技术(八)
前端·全栈·next.js