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

本文介绍了如何在React应用中使用`react-activation`库进行依赖安装、AliveScope包裹根组件、组件和路由的缓存,以及keepAlive属性的使用方法,还提供了手动刷新和清除缓存的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装依赖

npm i -S react-activation

2.使用AliveScope 包裹根组件

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.缓存组价或者路由

缓存组件

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>
}

缓存路由

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属性

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

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

类组件

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 )

函数组件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值