react-元件-keep-alive
阿新 • • 發佈:2022-04-12
目的:路由切換時,元件只是隱藏,而不要銷燬,以達到快取的目的。
實現原理:在切換路由時,讓頁面不解除安裝,而是通過 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 ( <div className='keep-alive' style={{ display: props.match ? 'block' : 'none' }} > {children} </div> ) } return <Route path={path} {...rest} children={child} /> }
使用
對父級路由元件進行快取
app.tsx
<KeepAlive path="/home">
<Layout />
</KeepAlive>