react-组件-keep-alive


目的:路由切换时,组件只是隐藏,而不要销毁,以达到缓存的目的。

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

keep-alive封装

KeepAlive/KeepAlive.tsx

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)
    return (
      
{children}
) } return }

使用

对父级路由组件进行缓存

app.tsx