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

相关推荐
烛阴33 分钟前
秒懂 JSON:JavaScript JSON 方法详解,让你轻松驾驭数据交互!
前端·javascript
拉不动的猪41 分钟前
刷刷题31(vue实际项目问题)
前端·javascript·面试
zeijiershuai43 分钟前
Ajax-入门、axios请求方式、async、await、Vue生命周期
前端·javascript·ajax
恋猫de小郭1 小时前
Flutter 小技巧之通过 MediaQuery 优化 App 性能
android·前端·flutter
只会写Bug的程序员1 小时前
面试之《webpack从输入到输出经历了什么》
前端·面试·webpack
拉不动的猪1 小时前
刷刷题30(vue3常规面试题)
前端·javascript·面试
狂炫一碗大米饭1 小时前
面试小题:写一个函数实现将输入的数组按指定类型过滤
前端·javascript·面试
最胖的小仙女1 小时前
通过动态获取后端数据判断输入的值打小
开发语言·前端·javascript
yzhSWJ1 小时前
Vue 3 中,将静态资源(如图片)转换为 URL
前端·javascript·vue.js
Moment1 小时前
🏞 JavaScript 提取 PDF、Word 文档图片,非常简单,别再头大了!💯💯💯
前端·javascript·react.js