介绍

这个项目是一个商城的后台管理系统,用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文档

到此这篇关于使用react-activation实现keepAlive支持返回传参的文章就介绍到这了,更多相关react-activation keepAlive返回传参内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

使用react-activation实现keepAlive支持返回传参的更多相关文章

  1. 如何在Android中设置keepalive超时?

    看起来我可以这样做,如果我使用NDK,但我想将此代码分发为jar,所以这对我来说并不理想.解决方法这可能是一个非常明显的答案[即它不是你特定案例的选项]但是你当然可以通过每10分钟发送1个丢弃字节来实现你自己的keepalive.

  2. 五分钟理解keep alive用法及原理

    这篇文章主要为大家介绍了keep alive用法及原理示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  3. Vue3-KeepAlive,多个页面使用keepalive方式

    这篇文章主要介绍了Vue3-KeepAlive,多个页面使用keepalive方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  4. vue3中使用router4 keepalive的问题

    这篇文章主要介绍了vue3中使用router4 keepalive的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  5. vue自定义keepalive组件的问题解析

    这篇文章主要介绍了vue自定义keepalive组件的相关资料,keep-alive组件是使用 include exclude这两个属性传入组件名称来确认哪些可以被缓存的,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  6. vue项目keepAlive配合vuex动态设置路由缓存方式

    vue项目keepAlive配合vuex动态设置路由缓存方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  7. Vue项目中keepAlive的使用说明(超级实用版)

    这篇文章主要介绍了Vue项目中keepAlive的使用说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  8. Vue设置keepAlive不生效问题及解决

    这篇文章主要介绍了Vue设置keepAlive不生效问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  9. react-router-dom v6 通过outlet实现keepAlive 功能的实现

    本文主要介绍了react-router-dom v6 通过outlet实现keepAlive功能,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. 使用react-activation实现keepAlive支持返回传参

    本文主要介绍了使用react-activation实现keepAlive支持返回传参,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部