1.安装依赖
npm i -S react-activation
2.使用AliveScope 包裹根组件
import { AliveScope } from "react-activation"
3.缓存组价或者路由
缓存组件
import { KeepAlive } from "react-activation"
export default () => {
const [isShow, setIsShow] = useState(true)
return
{
isShow &&
}
}
缓存路由
import KeepAlive from 'react-activation'
//name属性,是为了刷新时候,判断路由
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() 获取所有缓存中的节点
文章来源
发表评论