react中如何实现组件保存(keep-alive)

1,404 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第30天,点击查看活动详情

目的

为了优化用户的体验,可能会遇到这样的需求:返回列表的时候,需要保持状态和滚动位置;或是页面内切换组件(比如切换 Tab )的时候,需要保持状态。

如果使用 Vue,就可以用 组件来让其包含的组件保留状态,实现组件缓存。但是在 React 中并没有这样的功能,而且在这个 issues 中也可以看到,官方认为 容易造成内存的泄露,因此不准备引入这样的 API,但也许未来会提供更好的缓存方式,所以目前还需通过其他方法实现这类需求。

路由切换时,组件只是隐藏,而不要销毁,以达到缓存,避免重新渲染的目的。

vue

在 created 函数调用时将需要缓存的 VNode 节点保存在 this.cache 中,在 render(页面渲染) 时,如果 VNode 的 name 符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染

直接配置:

<keep-alive>
 <router-view></router-view>
</keep-alive>

react

手动保存

利用react的componentWillUnmount的生命周期在redux进行保存,然后通过componentDidMount生命周期恢复

自动保存

思路:

通过路由来实现,封装一个自定义路由,来实现即可

实现原理:在切换路由时,让页面不卸载,而是通过 display none 隐藏掉。这样,因为页面没有卸载,所以原来所有的操作都会被保存下来。 将来再返回该页面,只需要 display block 展示即可。这样,就可以恢复原来的内容了

例如:

1.Switch之外的Route中如果设置了children属性,且值是函数,此时,这个函数一定会执行;

<Route path="/any-path" children={()=><div>child</div>}></Route>

2.Switch之内的Route中如果设置了children属性,且值是函数,此时,它的path匹配优先级是最低的。

封装keep-alive

import React from 'react'
import { Route, RouteChildrenProps, RouteProps } from 'react-router'
type Props = RouteProps
export default function KeepAlive ({ path, children, ...rest }: Props) {
 const child = (props: RouteChildrenProps) => {
   console.log('child....', props)
   // const isMatch = props.location.pathname.startsWith(path as string)
   return (
     <div
       className="keep-alive"
       style={{ display: props.match ? 'block' : 'none' }}>
       {children}
     </div>
   )
 }

 return <Route path={path} {...rest} children={child} />
}

使用

app.jsx

<KeepAlive path="/home">
  <Layout />
</KeepAlive>

home.jsx

<KeepAlive path="/home" exact>
   <Home />
</KeepAlive>