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

 更新时间:2022年05月18日 11:29:44   作者:佟舟  
本文主要介绍了使用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文档

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

相关文章

  • React+valtio响应式状态管理

    React+valtio响应式状态管理

    Valtio是一个很轻量级的响应式状态管理库,使用外部状态代理去驱动React视图来更新,本文主要介绍了React+valtio响应式状态管理,感兴趣的可以了解一下
    2023-12-12
  • 深入理解React State 原理

    深入理解React State 原理

    本文主要介绍了React State 原理,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • react实现鼠标悬停在SVG地图上某个区域时上方呈现柱形图效果

    react实现鼠标悬停在SVG地图上某个区域时上方呈现柱形图效果

    这篇文章主要介绍了react实现鼠标悬停在SVG地图上某个区域时,其上方呈现柱形图,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2025-04-04
  • React中父组件如何获取子组件的值或方法

    React中父组件如何获取子组件的值或方法

    这篇文章主要介绍了React中父组件如何获取子组件的值或方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • React Fiber与调和深入分析

    React Fiber与调和深入分析

    Fiber可以理解为一个执行单元,每次执行完一个执行单元,React Fiber就会检查还剩多少时间,如果没有时间则将控制权让出去,然后由浏览器执行渲染操作,这篇文章主要介绍了React Fiber架构原理剖析,需要的朋友可以参考下
    2022-11-11
  • 基于React封装一个层次模糊效果的容器组件

    基于React封装一个层次模糊效果的容器组件

    这篇文章主要为大家详细介绍了如何基于React封装一个层次模糊效果的容器组件,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-03-03
  • 一文详解React渲染优化之useImmer

    一文详解React渲染优化之useImmer

    在React日常开发中,我们常常被重复渲染或无意义渲染所折磨,穷尽脑汁,做各种优化:memo、useMemo、useCallback、immutable等,本文主要讲述immutable的简约版Immer,感兴趣的同学可以一起来学习
    2023-05-05
  • React应用中避免白屏现象的方法小结

    React应用中避免白屏现象的方法小结

    在开发React应用程序时,我们都曾遇到过这样的场景:一个未被捕获的异常突然中断了组件的渲染流程,导致用户界面呈现出一片空白,也就是俗称的“白屏”现象,本文将探讨如何在React应用中有效捕获并处理这些错误,避免白屏现象的发生,需要的朋友可以参考下
    2024-06-06
  • react-redux中connect的装饰器用法@connect详解

    react-redux中connect的装饰器用法@connect详解

    这篇文章主要介绍了react-redux中connect的装饰器用法@connect详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-01-01
  • 浅谈react路由传参的几种方式

    浅谈react路由传参的几种方式

    这篇文章主要介绍了浅谈react路由传参的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03

最新评论