使用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避免子组件无效刷新的三种解决方案

    React避免子组件无效刷新的三种解决方案

    这篇文章主要给大家介绍了React三种避免子组件无效刷新的解决方案,使用React.memo,使用React.useMemo或React.useCallback,将子组件作为children来传递这三种方案,文章通过代码介绍的非常详细,需要的朋友可以参考下
    2023-08-08
  • 从零开始学习搭建React脚手架项目

    从零开始学习搭建React脚手架项目

    这篇文章主要介绍了从零开始学习搭建React脚手架项目,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • 如何去除富文本中的html标签及vue、react、微信小程序中的过滤器

    如何去除富文本中的html标签及vue、react、微信小程序中的过滤器

    这篇文章主要介绍了如何去除富文本中的html标签及vue、react、微信小程序中的过滤器,在vue及react中经常会遇到,今天通过实例代码给大家讲解,需要的朋友可以参考下
    2018-11-11
  • react fiber使用的关键特性及执行阶段详解

    react fiber使用的关键特性及执行阶段详解

    这篇文章主要为大家介绍了react fiber使用的关键特性及执行阶段详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 浅谈react-router HashRouter和BrowserRouter的使用

    浅谈react-router HashRouter和BrowserRouter的使用

    本篇文章主要介绍了浅谈react-router HashRouter和BrowserRouter的使用,具有一定的参考价值,有兴趣的可以了解一下
    2017-12-12
  • 使用React Hooks模拟生命周期的实现方法

    使用React Hooks模拟生命周期的实现方法

    这篇文章主要介绍了使用React Hooks模拟生命周期,本文举例说明如何使用 hooks 来模拟比较常见的 class 组件生命周期,需要的朋友可以参考下
    2023-02-02
  • 详解在React项目中如何集成和使用web worker

    详解在React项目中如何集成和使用web worker

    在复杂的React应用中,某些计算密集型或耗时操作可能会阻塞主线程,导致用户界面出现卡顿或响应慢的现象,为了优化用户体验,可以采用Web Worker来在后台线程中执行这些操作,本文将详细介绍在React项目中如何集成和使用Web Worker来改善应用性能,需要的朋友可以参考下
    2023-12-12
  • React 小技巧教你如何摆脱hooks依赖烦恼

    React 小技巧教你如何摆脱hooks依赖烦恼

    Hooks 是一种函数,该函数允许您从函数式组件 “勾住(hook into)” React 状态和生命周期功能。 Hooks 在类内部不起作用 - 它们允许你无需类就使用 React,本文带领大家学习React 小技巧教你如何摆脱hooks依赖烦恼,感兴趣的朋友一起看看吧
    2021-05-05
  • React Fiber构建源码解析

    React Fiber构建源码解析

    这篇文章主要为大家介绍了React Fiber构建源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • React中上传图片到七牛的示例代码

    React中上传图片到七牛的示例代码

    本篇文章主要介绍了React中上传图片到七牛的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10

最新评论