使用 react-activation 实现 keepAlive,并支持返回传递。
更新
2022.06.01更新
请移步到最终版本:react-activation实现keepAlive,支持返回传参(最终版)
介绍
这个项目是一个商城的后台管理系统,用umi2.0
搭建,状态管理使用dva
,想要实现类似vue keep-alive
的效果。
具体表现为:
- 从列表页A跳转A的详情页,列表页A缓存
- 详情页没做任何操作,跳回列表页A,列表页A不刷新,列表页A页码不变
- 详情页进行了
编辑
操作,跳回列表页A,列表页A刷新,列表页A页码不变 - 详情页进行了
新建
操作,跳回列表页A,列表页A刷新,列表页A页码变为1
- 从列表页A跳转列表页B,列表页A不缓存
总结就是,一个页面只有跳转指定页面的时候才缓存,并且当返回这个被缓存的页面时,可以控制是否刷新。
代码
1、安装react-activation
"react-activation": "^0.10.2",
2、给路由增加meta
这个项目使用的是集中式配置路由,我增加了meta属性,meta.keepAlive
存在表示这是一个需要被keepAlive的路由,meta.keepAlive.toPath
表示只有当前往这个路由的时候,需要缓存
const routes = [
...
{
name: '商品管理(商城商品)',
path: '/web/supplier/goods/mallgoodsmgr',
component: './supplier/goods/goodsManage',
meta: {
keepAlive: {
toPath: '/web/supplier/goods/mallgoodsmgr/detail', // 只有去详情页的时候 才需要缓存 商品管理(商城商品)这个路由
},
},
}
...
]
3、根组件中渲染
在根组件中,用<AliveScope/>
包裹整个应用,用<KeepAlive/>
包裹需要缓存的页面。文档中这部分写在<App/>
中,如果是umi可以写在layouts里。
通过tree的扁平化计算获取全部的带有meta.keepAlive的routes:keepAliveRoutes
,通过location.pathname
判断,如果当前页面是需要keepAlive的,那么就需要用<KeepAlive/>
包裹。
import KeepAlive, { AliveScope, useAliveController } from 'react-activation'
// tree扁平化
function treeToList(tree, childrenKey = 'routes') {
var queen = []
var out = []
queen = queen.concat(tree)
while (queen.length) {
var first = queen.shift()
if (first[childrenKey]) {
queen = queen.concat(first[childrenKey])
delete first[childrenKey]
}
out.push(first)
}
return out
}
// 从routes路由tree里,拿到所有meta.keepAlive的路由:keepAliveRoutes
const allFlatRoutes = treeToList(routes) // 所有路由
const keepAliveRoutes = allFlatRoutes.filter((item) => item.meta?.keepAlive) // keepAlive的路由
function Index(props) {
const location = useLocation()
const routeItem = keepAliveRoutes.find(
(item) => item.path == location.pathname
) // from 页面
let dom = props.children
if (routeItem) {
dom = <KeepAlive id={location.pathname}>{props.children}</KeepAlive> // id 一定要加 否则 keepAlive的页面 跳转 另一个keepAlive的页面 会有问题
}
return (
<AliveScope>
<div className={styles.page_container}>{dom}</div>
</AliveScope>
)
}
注意AliveScope中包含多个
KeepAlive的话,<KeepAlive/>
一定要带id
。
4、跳转指定页面的时候才缓存
上一步之后,页面虽然被缓存,但是它跳转任何页面都会缓存,我们需要只有跳转指定页面的时候才缓存。
我的方法是
- 如果跳转的页面正好是它自己的
meta.keepAlive.toPath
,那就不做任何操作(因为此时本页面已经被KeepAlive包裹了,处于缓存的状态) - 如果不是它自己的
meta.keepAlive.toPath
,调用clear
方法,清空缓存
4.1 clear方法
react-activation提供useAliveController
可以手动控制缓存,其中clear
方法用于清空所有缓存中的 KeepAlive
4.2 用状态管理记录toPath
监听history,用状态管理(我用的dva)记录即将前往的页面(下一个页面)toPath
我通过dva
记录应用即将前往的页面
const GlobalModel = {
namespace: 'global',
state: {
/**
* keepAlive
*/
toPath: '',
keepAliveOptions: {}, // 给keepAlive的页面 传的options
},
effects: {},
reducers: {
save(state, { payload }) {
return {
...state,
...payload,
}
},
setToPath(state, { payload }) {
return {
...state,
toPath: payload,
}
},
},
subscriptions: {
setup({ history, dispatch }) {
// Subscribe history(url) change, trigger `load` action if pathname is `/`
history.listen((route, typeStr) => {
const { pathname } = route
dispatch({
type: 'setToPath',
payload: pathname,
})
})
},
},
}
4.3 给根组件增加useEffect
根组件从dva中读取即将访问的页面toPath,然后加一个useEffect
,如果即将前往的页面不是当前路由自己的meta.keepAlive.toPath,就执行react-activation
提供的clear
方法
...
function Index(props) {
const location = useLocation()
const toPath = props.global.toPath // 从dva中拿到 将要访问的页面
const routeItem = keepAliveRoutes.find(
(item) => item.path == location.pathname
) // from 页面
/// 新加代码
/// 新加代码
/// 新加代码
useEffect(() => {
console.log('toPath改变', toPath)
// from页面 是需要keepAlive的页面
if (routeItem) {
console.log('from页面 是需要keepAlive的页面', routeItem)
if (toPath == routeItem.meta?.keepAlive.toPath) {
// 所去的 页面 正好是当前这个路由的 keepAlive.toPath
console.log('所去的 页面 正好是当前这个路由的 keepAlive.toPath,不做什么')
} else {
console.log('clear')
if (aliveController?.clear) {
aliveController.clear()
}
}
}
}, [toPath])
/// 新加代码 end
let dom = props.children
if (routeItem) {
dom = <KeepAlive id={location.pathname}>{props.children}</KeepAlive> // id 一定要加 否则 keepAlive的页面 跳转 另一个keepAlive的页面 会有问题
}
return (
<AliveScope>
<div className={styles.page_container}>{dom}</div>
</AliveScope>
)
}
export default connect(({ global, login }) => ({ global, login }))(Index)
4.4 优化
现在有一个问题:从列表A跳转详情页,然后跳转列表B,再跳转列表A的时候,A是不刷新的:
列表A
=> 详情页
=> 列表B
=> 列表A
此时列表A
不刷新或者空白。
因为从详情页
出来(跳转列表B)的时候,我们没有清空列表A的缓存。
所以要检查当前页面是否是某个需要keepAlive页面的toPath页面
根组件:
function Index(){
...
const parentItem = keepAliveRoutes.find((item) => item.meta?.keepAlive?.toPath == location.pathname) // parentItem存在表示 当前页面 是某个keepAlive的页面 的toPath
useEffect(() => {
console.log('toPath改变', toPath)
...
/// 新加代码
/// 新加代码
/// 新加代码
// from页面 是某个keepAlive的页面 的toPath
if (parentItem) {
console.log('from页面 是某个keepAlive的页面 的toPath,parentItem', parentItem)
if (toPath == parentItem.path) {
// 所去的 页面是 parentItem.path
console.log('所去的 页面是 parentItem.path,不做什么')
} else {
console.log('clear')
if (aliveController?.clear) {
aliveController.clear()
}
}
}
}, [toPath])
...
}
5、抽离逻辑到自定义hooks
useKeepAliveLayout.js
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import KeepAlive, { AliveScope, useAliveController } from 'react-activation'
import routes from '../../config/router.config'
// tree扁平化
function treeToList(tree, childrenKey = 'routes') {
var queen = []
var out = []
queen = queen.concat(tree)
while (queen.length) {
var first = queen.shift()
if (first[childrenKey]) {
queen = queen.concat(first[childrenKey])
delete first[childrenKey]
}
out.push(first)
}
return out
}
const allFlatRoutes = treeToList(routes) // 所有路由
const keepAliveRoutes = allFlatRoutes.filter((item) => item.meta?.keepAlive) // keepAlive的路由
function index(props) {
const location = useLocation()
// keep alive
const aliveController = useAliveController()
const toPath = props.global.toPath // 将要访问的页面
const routeItem = keepAliveRoutes.find((item) => item.path == location.pathname) // from 页面
const parentItem = keepAliveRoutes.find((item) => item.meta?.keepAlive?.toPath == location.pathname)
useEffect(() => {
console.log('toPath改变', toPath)
// from页面 是需要keepAlive的页面
if (routeItem) {
console.log('from页面 是需要keepAlive的页面', routeItem)
if (toPath == routeItem.meta?.keepAlive.toPath) {
// 所去的 页面 正好是当前这个路由的 keepAlive.toPath
console.log('所去的 页面 正好是当前这个路由的 keepAlive.toPath,不做什么')
} else {
console.log('clear')
if (aliveController?.clear) {
aliveController.clear()
}
}
}
// from页面 是某个keepAlive的页面 的toPath
if (parentItem) {
console.log('from页面 是某个keepAlive的页面 的toPath,parentItem', parentItem)
if (toPath == parentItem.path) {
// 所去的 页面是 parentItem.path
console.log('所去的 页面是 parentItem.path,不做什么')
} else {
console.log('clear')
if (aliveController?.clear) {
aliveController.clear()
}
}
}
}, [toPath])
return {
fromIsNeedKeepAlive: routeItem,
}
}
export default index
根组件只需要引入这个hooks就可以了:
function Index(props) {
const location = useLocation()
const { fromIsNeedKeepAlive } = useKeepAliveLayout(props) // 关键代码关键代码关键代码
let dom = props.children
if (fromIsNeedKeepAlive) {
dom = <KeepAlive id={location.pathname}>{props.children}</KeepAlive> // id 一定要加 否则 keepAlive的页面 跳转 另一个keepAlive的页面 会有问题
}
return (
<AliveScope>
<div className={styles.page_container}>{dom}</div>
</AliveScope>
)
}
6、 从详情页返回列表页的时候,控制列表页是否刷新,即返回传参
现在只剩下这最后一个问题了,其实就是keepAlive的页面,goBack传参的问题
思路:
- 状态管理中增加一个keepAliveOptions对象,这就是详情页给列表页传的参数
- 详情页执行goBack的时候,调用状态管理dispatch修改keepAliveOptions
- 列表页监听keepAliveOptions,如果keepAliveOptions改变就执行传入的方法
useKeepAliveOptions.js
import { useEffect } from 'react'
import { useDispatch, useStore } from 'dva'
import { router } from 'umi'
/**
* @description keepAlive的页面,当有参数传过来的时候,可以用这个监听到
* @param {(options:object)=>void} func
*/
export function useKeepAlivePageShow(func) {
const dispatch = useDispatch()
const store = useStore()
const state = store.getState()
const options = state.global.keepAliveOptions ?? {}
useEffect(() => {
func(options) // 执行
return () => {
console.log('keepAlive页面 的缓存 卸载')
dispatch({
type: 'global/save',
payload: {
keepAliveOptions: {},
},
})
}
}, [JSON.stringify(options)])
}
/**
* @description PageA(keepAlive的页面)去了 PageB, 当从PageB goBack,想要给PageA传参的时候,需要使用这个方法
* @returns {(params:object)=>void}
*/
export function useKeepAliveGoback() {
const dispatch = useDispatch()
function goBack(parmas = {}) {
dispatch({
type: 'global/save',
payload: {
keepAliveOptions: parmas,
},
})
router.goBack()
}
return goBack
}
使用:
详情页
import { useKeepAliveGoback } from '@/hooks/useKeepAliveOptions'
function Index(){
...
const keepAliveGoback = useKeepAliveGoback() // 用于给上一页keepAlive的页面 传参
...
return (
<>
...
<button onClick={() => {
keepAliveGoback({ isAddSuccess: true }) // 给列表页传options
}></button>
...
</>
)
}
列表页
import { useKeepAlivePageShow } from '@/hooks/useKeepAliveOptions'
function Index(){
...
// options: isAddSuccess isEditSuccess
useKeepAlivePageShow((options) => {
console.log('keepAlive options', options)
if (options.isAddSuccess) {
// 新建成功 // 列表页码变为1 并且刷新
search()
} else if (options.isEditSuccess) {
// 编辑成功 // 列表页码不变 并且刷新
getData()
}
})
...
return <>...</>
}
相关文档
- react-activation
- dva文档
下一篇: 2017-10-23
推荐阅读
-
35 岁实现财务*,腾讯程序员手握2300万提前退休?-1000万房产、1000万腾讯股票、加上300万的现金,一共2300万的财产。有网友算了一笔账,假设1000万的房产用于自住,剩下1300万资产按照平均税后20-50万不等进行计算,大约花上26-60年左右的时间才能赚到这笔钱。也就是说,普通人可能奋斗一辈子,才能赚到这笔钱。在很多人还在为中年危机而惶惶不可终日的时候,有的人的35岁,就已经安全着陆,试问哪个打工人不羡慕?但问题是有这样财富积累必然有像样的实力做靠山。没有人可以不劳而获。 看到这里,肯定有人说,那么对于普通人来说,卷可能真就成了唯一的出路。但是卷也有轻松的卷,“偷懒”的卷法,对于程序员而言,刨除掉一时无法改掉的开会传统占用的大部分时间,如何把有限的时间和精力放在真正重要的架构设计、需求设计上,而不是重复的造*,编码、改bug、手动测试。因此在科技改变生活的今天,学会使用AI工具成为程序员们的必备技能。 以全栈式全自动的软件开发工具飞算SoFlu软件机器人为例,作为全球首款面向微服务架构设计和最佳实践的软件机器人,SoFlu软件机器人改变了原来手工编码的作业模式,通过可视化拖拽方式以及参数配置就能实现等同于编写复杂代码的业务逻辑,在设计业务逻辑时就完成了微服务应用开发,做到“业务即图,图即代码”,实现“软件开发,十倍提效”。 而作为飞算SoFlu软件机器人的一个重要组成部分,FuncGPT(慧函数)支持所有类型函数创建。通过自然语言描述Java函数需求,实时生成高质量、高可读性的Java函数代码。生成代码可直接复制到IDEA,或一键导入Java全自动开发工具函数库。 FuncGPT(慧函数)具有五大核心能力: ● 自然语言:通过自然语言即可生成函数,降低软件开发门槛。 ● 秒级函数开发:全自动秒级开发函数,秒级完成,效率千倍提升。 ● 一站式函数开发应用:函数生成即可直接应用,效率、安全有保障。 ● 质量可靠:生成的函数代码符合业界规范、具备良好的可读性,符合最优解。 ● 灵活生成:可以根据开发人员的具体需求生成并支持调整和修改。 以“将文件流转换为File对象”这个需求为例,以下是FuncGPT(慧函数)秒级生成的代码: / 类名:FileConverter // 函数名:convertStreamToFile // 函数功能:将文件流转换为File对象 // POM依赖包:无 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileConverter { /** * 将文件流转换为File对象 * @param inputStream 文件流 * @param filePath 文件路径 * @param fileName 文件名 * @return 转换后的File对象 * @throws IOException 如果发生I/O异常 */ public static File convertStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException { File file = new File(filePath + File.separator + fileName); // 创建File对象 try (FileOutputStream outputStream = new FileOutputStream(file)) { // 创建文件输出流 byte buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { // 从文件流读取数据并写入文件 outputStream.write(buffer, 0, bytesRead); } } return file; // 返回转换后的File对象 } } // 函数示例 // 将文件流转换为File对象示例 // 入参:inputStream,文件流 // 入参:filePath,文件路径 // 入参:fileName,文件名 // 出参:file,转换后的File对象 // 调用示例: // InputStream inputStream = new FileInputStream("example.txt"); // String filePath = "C:\\Users\\User\\Documents"; // String fileName = "example.txt"; // File file = FileConverter.convertStreamToFile(inputStream, filePath, fileName); // System.out.println(file.getAbsolutePath); // 输出结果:例如,将文件流转换为File对象后,文件的绝对路径为:C:\Users\User\Documents\example.txt // 则输出结果为:C:\Users\User\Documents\example.txt 通过分析,不难发现以上代码:
-
一种结构设计模式,允许在对象中动态添加新行为。它通过创建一个封装器来实现这一目的,即把对象放入一个装饰器类中,然后把这个装饰器类放入另一个装饰器类中,以此类推,形成一个封装器链。这样,我们就可以在不改变原始对象的情况下动态添加新行为或修改原始行为。 在 Java 中,实现装饰器设计模式的步骤如下: 定义一个接口或抽象类作为被装饰对象的基类。 公共接口 Component { void operation; } } 在本例中,我们定义了一个名为 Component 的接口,该接口包含一个名为 operation 的抽象方法,该方法定义了被装饰对象的基本行为。 定义一个实现基类方法的具体装饰对象。 公共类 ConcreteComponent 实现 Component { public class ConcreteComponent implements Component { @Override public void operation { System.out.println("ConcreteComponent is doing something...") ; } } 定义一个抽象装饰器类,该类继承于基类,并将装饰对象作为一个属性。 公共抽象类装饰器实现组件 { protected Component 组件 public Decorator(Component component) { this.component = component; } } @Override public void operation { component.operation; } } } 在这个示例中,我们定义了一个名为 Decorator 的抽象类,它继承了 Component 接口,并将被装饰对象作为一个属性。在操作方法中,我们调用了被装饰对象上的同名方法。 定义一个具体的装饰器类,继承自抽象装饰器类并实现增强逻辑。 公共类 ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component 组件) { super(component); } } public void operation { super.operation System.out.println("ConcreteDecoratorA 正在添加新行为......") ; } } 在本例中,我们定义了一个名为 ConcreteDecoratorA 的具体装饰器类,它继承自装饰器抽象类,并实现了操作方法的增强逻辑。在操作方法中,我们首先调用被装饰对象上的同名方法,然后添加新行为。 使用装饰器增强被装饰对象。 公共类 Main { public static void main(String args) { Component 组件 = new ConcreteComponent; component = new ConcreteDecoratorA(component); 组件操作 } } 在这个示例中,我们首先创建了一个被装饰对象 ConcreteComponent,然后通过 ConcreteDecoratorA 类创建了一个装饰器,并将被装饰对象作为参数传递。最后,调用装饰器的操作方法,实现对被装饰对象的增强。 使用场景 在 Java 中,装饰器模式被广泛使用,尤其是在 I/O 中。Java 中的 I/O 库使用装饰器模式实现了不同数据流之间的转换和增强。 让我们打开文件 a.txt,从中读取数据。InputStream 是一个抽象类,FileInputStream 是专门用于读取文件流的子类。BufferedInputStream 是一个支持缓存的数据读取类,可以提高数据读取的效率,具体代码如下: @Test public void testIO throws Exception { InputStream inputStream = new FileInputStream("C:/bbb/a.txt"); // 实现包装 inputStream = new BufferedInputStream(inputStream); byte bytes = new byte[1024]; int len; while((len = inputStream.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } } } } 其中 BufferedInputStream 对读取数据进行了增强。 这样看来,装饰器设计模式和代理模式似乎有点相似,接下来让我们讨论一下它们之间的区别。 第三,与代理模式的区别: 代理模式的目的是控制对对象的访问,它在对象外部提供一个代理对象来控制对原对象的访问。代理对象和原始对象通常实现相同的接口或继承相同的类,以确保两者可以相互替换。 装饰器模式的目的是动态增强对象的功能,而这是通过对象内部的包装器来实现的。在装饰器模式中,装饰器类和被装饰对象通常实现相同的接口或继承自相同的类,以确保两者可以相互替代。装饰器模式也被称为封装器模式。 在代理模式中,代理类附加了与原类无关的功能。
-
使用 react-activation 实现 keepAlive,并支持返回传递。
-
南邮OJ Web任务大揭秘:层层挑战剖析 1. 挑战一:迷宫般的目录探索 题目作者似乎穷举了所有可能的目录组合,最终在404.php中的