目标
路由切换时,组件只是隐藏,而不要销毁,以达到缓存的目的。
思路
通过路由来实现,封装一个自定义路由,来实现即可
实现原理:在切换路由时,让页面不卸载,而是通过 display none 隐藏掉。这样,因为页面没有卸载,所以原来所有的操作都会被保存下来。 将来再返回该页面,只需要 display block 展示即可。这样,就可以恢复原来的内容了
背景知识
1.Switch之外的Route中如果设置了children属性,且值是函数,此时,这个函数一定会执行;
<Route path="/any-path" children={()=><div>child</div>}></Route>
2.Switch之内的Route中如果设置了children属性,且值是函数,此时,它的path匹配优先级是最低的。
keep-alive封装
/* eslint-disable react/no-children-prop */
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>