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

相关推荐
谢彦超oooo21 小时前
HTML5 与前端开发要点
前端·html·html5
IT_陈寒21 小时前
Vue 3响应式原理深度拆解:5个90%开发者不知道的Ref与Reactive底层实现差异
前端·人工智能·后端
小马爱打代码21 小时前
MyBatis:进阶 - 动态 SQL、关联查询与缓存
sql·缓存·mybatis
睡前要喝豆奶粉21 小时前
在.NET Core Web Api中使用JWT并配置UserContext获取用户信息
前端·.netcore
前端加油站21 小时前
一份实用的Vue3技术栈代码评审指南
前端·vue.js
Jonathan Star1 天前
沉浸式雨天海岸:用A-Frame打造WebXR互动场景
前端·javascript
工业甲酰苯胺1 天前
实现 json path 来评估函数式解析器的损耗
java·前端·json
老前端的功夫1 天前
Web应用的永生之术:PWA落地与实践深度指南
java·开发语言·前端·javascript·css·node.js
LilySesy1 天前
ABAP+WHERE字段长度不一致报错解决
java·前端·javascript·bug·sap·abap·alv
Wang's Blog1 天前
前端FAQ: Vue 3 与 Vue 2 相⽐有哪些重要的改进?
前端·javascript·vue.js