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

本文主要介绍了react-router-dom v6 通过outlet实现keepAlive 功能的实现,具体如下:

keepAlive代码:

import React, { useRef, useEffect, useReducer, useMemo, memo } from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { useLocation } from 'react-router-dom'

const KeepAlive = props => {
    const { include, keys, children } = props
    const { pathname } = useLocation()
    const componentList = useRef(new Map())
    const forceUpdate = useReducer(bool => !bool)[1] // 强制渲染
    const cacheKey = useMemo(() => pathname + "__" + keys[pathname], [pathname, keys]) // eslint-disable-line
    const activeKey = useRef(null)

    useEffect(() => {
        componentList.current.forEach(function(value, key) {
            const _key = key.split("__")[0]
            if (!include.includes(_key) || (_key === pathname)) {
                this.delete(key)
            }
        }, componentList.current)

        activeKey.current = cacheKey
        if (!componentList.current.has(activeKey.current)) {
            componentList.current.set(activeKey.current, children)
        }
        forceUpdate()
    }, [cacheKey, include]) // eslint-disable-line

    return (
        <TransitionGroup component={ null }>
            {
                Array.from(componentList.current).map(([key, component]) =>
                    <CSSTransition
                        key={ key }
                        appear={ true }
                        timeout={ 500 }
                        classNames='fade'>
                        {
                            key === activeKey.current ?
                            <div
                                className={
                                    `layout-container${include.includes(key.split("__")[0]) ? " keep-alive-fade": ""}`
                                }>
                                { component }
                            </div> :
                            <div
                                className='layout-container__keep-alive'
                                style={{ display: 'none' }}>
                                { component }
                            </div>
                        }
                    </CSSTransition>
                )
            }
        </TransitionGroup>
    )
}

export default memo(KeepAlive)

main.js 中调用

import PropTypes from 'prop-types'
import { useLocation, useOutlet } from 'react-router-dom'
import { connect } from 'react-redux'
import { Layout } from 'antd'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import KeepAlive from '@/components/common/keepAlive'
import { isKeepAlive } from '@/service/config'

const Main = props => {
    const { fullScreen, cacheRoutes, cacheKeys } = props
    const outlet = useOutlet()
    const { pathname } = useLocation()

    return (
        <Layout.Content className={{ "layout-main": true, "full-screen": fullScreen }}>
            <section>
                {
                	// isKeepAlive 生产环境中启用缓存
                    isKeepAlive ?
                    <KeepAlive include={ cacheRoutes } keys={ cacheKeys }>
                        { outlet } // 此处不能用 <Outlet /> 不然无法通过 useRef 来缓存
                    </KeepAlive> :
                    <TransitionGroup component={ null }>
                        <CSSTransition
                            key={ pathname + cacheKeys[pathname] }
                            appear={ true }
                            timeout={ 500 }
                            classNames='page-fade'>
                            { outlet } // 此处不能用 <Outlet /> 会造成路由切换时,组件重复渲染
                        </CSSTransition>
                    </TransitionGroup>
                }
            </section>
        </Layout.Content>
    )
}

Main.propTypes = {
    fullScreen: PropTypes.bool,
    cacheRoutes: PropTypes.array,
    cacheKeys: PropTypes.object
}

const mapStateToProps = state => {
    return {
        fullScreen: state.setting.fullScreen,
        cacheRoutes: state.tabsBar.cacheRoutes, // 需要缓存的路由组件path数组
        cacheKeys: state.tabsBar.cacheKeys // 用于组件局部刷新
    }
}

export default connect(mapStateToProps)(Main)

1、当前图片动画中,只设置了第二个标签页缓存,其他的几个未开启缓存,所以可以看到,只有第二个标签页在切回的时候 未重新请求数据。其他标签页每次进入都会重新请求数据。
2、此外这里结合react-transition-group 实现了路由切换的渐隐渐显动画,但需要手动配合css样式控制,不能完全依靠CSSTransition
代码部分:

// 路由进入动画
.fade-enter, .fade-appear {
    opacity: 0;
}
.fade-enter-active, .fade-appear-active {
    opacity: 1;
    @include transition(opacity .25s cubic-bezier(.645, .045, .355, 1) .25s);
}
.fade-exit {
    opacity: 1;
    z-index: 1;
}
.fade-exit-active {
    opacity: 0;
    z-index: 1;
    @include transition(opacity .25s cubic-bezier(.645, .045, .355, 1));
}
.page-fade-enter, .page-fade-appear {
    opacity: 0;
}
.page-fade-enter-active, .page-fade-appear-active {
    opacity: 1;
    @include transition(opacity .5s cubic-bezier(.645, .045, .355, 1));
}
.page-fade-exit {
    opacity: 1;
    display: none!important;
}
.page-fade-exit-active {
    opacity: 0;
}
@keyframes keepAliveFade {
  0% { opacity: 0; }
  50% { opacity: 0; }
  100% { opacity: 1; }
}
.layout-container {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    &.keep-alive-fade { animation: keepAliveFade .5s ease-in-out; }
}

到此这篇关于react-router-dom v6 通过outlet实现keepAlive 功能的实现的文章就介绍到这了,更多相关react-router keepAlive 内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • react-router-domV6版本的路由和嵌套路由写法详解

    目录 1-单级路由 2-嵌套路由(about路径进行嵌套) ReactRouterv6使用路由嵌套和重定向 1 - 单级路由 <NavLink to="/home">Home</NavLink> <NavLink to="/about">about</NavLink> <Routes>   <Route path='/home' element={<Home/>}/>   <R

  • react-router-dom V6的配置使用实践

    目录 一.关于书写方面 二.路由的嵌套方面优化 三.关于路由的灵活配置化 四.关于路由鉴权方面 最近在搭建PC项目的React框架,涉及到React Router,开发同学有时就需要去尝试点新的东西,在开发过程中才不会枯燥的,基于这个理念推动,就在搭建的时候用V6的版本开始了(虽然只是个新版本,也不算啥新东西)...... V6的版本相对于V5,做了很多的优化,有书写方面的.路由的嵌套.路由配置化.鉴权方面等等,下面就简单的介绍下如何使用 一.关于书写方面 路由注册的时候由的Switch改为了R

  • 详解react-router-dom v6版本基本使用介绍

    目录 Routes Route Navigate NavLink useRoutes 嵌套路由 路由传参 编程式导航 Routes 代替Switch组件,不会向下匹配 用来包裹Route Route 必须被Routes组件包裹 component属性变成element caseSensitive 路径大小写敏感属性,默认是不敏感(访问/about = /ABOUT) index 与path属性是互斥的,index表示为当前路由的根 可以用作layout组件,不写element属性,写了要与 Ou

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

    本文主要介绍了react-router-dom v6 通过outlet实现keepAlive 功能的实现,具体如下: keepAlive代码: import React, { useRef, useEffect, useReducer, useMemo, memo } from 'react' import { TransitionGroup, CSSTransition } from 'react-transition-group' import { useLocation } from 'r

  • React Router V6更新内容详解

    目录 ReactRouterV6变更介绍 1.<Switch>重命名为<Routes> 2.<Route>的新特性变更 3.嵌套路由变得更简单 3.1具体变化有以下: 3.2废弃了V5中的Redirect 3.3多个<Routes/> 4.用useNavigate代替useHistory 5.Hooks中新钩子useRoutes代替react-router-config 总结 React Router V6 变更介绍 之前一直在用5.x版本的Router,突

  • 使用React Router v6 添加身份验证的方法

    目录 开始 基础路由 创建受保护的路由 使用嵌套路由和< Outlet /> 结尾 React Router v6是React应用程序的一个流行且功能强大的路由库.它提供了一种声明式的.基于组件的路由方法,并能处理URL参数.重定向和加载数据等常见任务. 这个最新版本的React Router引入了很多新概念,比如<Outlet />和layout布局路由,但相关文档仍然很少. 本文将演示如何使用React Router v6创建受保护的路由以及如何添加身份验证. 开始 打开终端,

  • react router零基础使用教程

    目录 安装 配置路由 添加一个新页面测试路由 配置未找到的路由 跳转页面 通过 js 通过 dom 嵌套页面 安装 既然学习 react router 就免不了运行 react 安装 react npx create-react-app my-appcd my-appnpm start 安装 react router npm install react-router-dom 如果一切正常,就让我们打开 index.js 文件. 配置路由 引入 react-router-dom 的 RouterP

  • React Router v4 入坑指南(小结)

    距离React Router v4 正式发布也已经过去三个月了,这周把一个React的架子做了升级,之前的路由用的还是v2.7.0版的,所以决定把路由也升级下,正好"尝尝鲜"... 江湖传言,目前官方同时维护 2.x 和 4.x 两个版本.(ヾ(。ꏿ﹏ꏿ)ノ゙咦,此刻相信机智如我的你也会发现,ReactRouter v3 去哪儿了?整丢了??巴拉出锅了???敢不敢给我个完美的解释!?)事实上 3.x 版本相比于 2.x 并没有引入任何新的特性,只是将 2.x 版本中部分废弃 API 的

  • React Router基础使用

    React是个技术栈,单单使用React很难构建复杂的Web应用程序,很多情况下我们需要引入其他相关的技术 React Router是React的路由库,保持相关页面部件与URL间的同步 下面就来简单介绍其基础使用,更全面的可参考 指南 1. 它看起来像是这样 在页面文件中 在外部脚本文件中 2. 库的引入 React Router库的引入,有两种方式 2.1 浏览器直接引入 可以引用 这里 的浏览器版本,或者下载之后引入 然后就可以直接使用 ReactRouter 这个对象了,我们可能会使用到

  • react router 4.0以上的路由应用详解

    本文介绍了react router 4.0以上的路由应用,分享给大家,具体如下: 在4.0以下的react router中,嵌套的路由可以放在一个router标签中,形式如下,嵌套的路由也直接放在一起. <Route component={App}> <Route path="groups" components={Groups} /> <Route path="users" components={Users}> <Rou

  • React路由管理之React Router总结

    React项目通常都有很多的URL需要管理,最常使用的解决方案就是React Router了,最近学习了一下,主要是看了一下官方的英文文档,加以总结,以备后查. React Router是做什么的呢,官方的介绍是: A complete routing library for React,keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dy

  • React router动态加载组件之适配器模式的应用详解

    前言 本文讲述怎么实现动态加载组件,并借此阐述适配器模式. 一.普通路由例子 import Center from 'page/center'; import Data from 'page/data'; function App(){ return ( <Router> <Switch> <Route exact path="/" render={() => (<Redirect to="/center" />)}

  • React Router V4使用指南(精讲)

    一.前端路由和后端路由 1)后端路由 多页应用中,一个URL对应一个HTML页面,一个Web应用包含很多HTML页面,在多页应用中,页面路由控制由服务器端负责,这种路由方式称为后端路由. 多页应用中,每次页面切换都需要向服务器发送一次请求,页面使用到的静态资源也需要重新加载,存在一定的浪费.而且,页面的整体刷新对用户体验也有影响,因为不同页面间往往存在共同的部分,例如导航栏.侧边栏等,页面整体刷新也会导致共用部分的刷新. 2)前端路由 在单面应用中,URL发生并不会向服务器发送新的请求,所以"逻

随机推荐