react 自定义封装组件 实现keep-alive

目标

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

思路

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

实现原理:在切换路由时,让页面不卸载,而是通过 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) => {
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React封装一个类似于 Vue 中的 `keep-alive` 的组件可以使用 React 的上下文(Context)和 React 组件的生命周期方法。 首先,创建一个上下文(Context)来保存需要缓存的组件的状态。这个上下文可以在应用的最顶层的组件中创建,如 App 组件。在这个上下文中,保存一个对象,用于存储需要缓存的组件的状态。 其次,创建一个高阶组件(Higher-Order Component),用于将需要缓存的组件包裹起来。这个高阶组件会在组件挂载时,在上下文中保存组件的状态,如果组件已经挂载过了,则直接从上下文中获取组件的状态。 最后,使用这个高阶组件来包裹需要缓存的组件即可。 一个简单的示例代码如下: ``` import React, { createContext, useContext } from 'react'; const CacheContext = createContext({}); function withKeepAlive(WrappedComponent) { return class extends React.Component { static contextType = CacheContext; constructor(props, context) { super(props, context); const { cache } = context; if (cache[WrappedComponent.name]) { this.state = cache[WrappedComponent.name]; } else { this.state = { ...this.state, mounted: false, }; } } componentDidMount() { this.setState({ mounted: true, }); } componentWillUnmount() { const { cache } = this.context; if (this.state.mounted) { cache[WrappedComponent.name] = this.state; } } render() { return <WrappedComponent {...this.props} />; } }; } function KeepAliveProvider({ children }) { const cache = {}; return ( <CacheContext.Provider value={{ cache }}> {children} </CacheContext.Provider> ); } function KeepAlive({ children }) { const KeepAliveComponent = withKeepAlive(children.type); return <KeepAliveComponent {...children.props} />; } export { KeepAliveProvider, KeepAlive }; ``` 使用时,可以将需要缓存的组件用 `KeepAlive` 组件包裹起来,并在应用的最顶层使用 `KeepAliveProvider` 组件包裹整个应用,如下所示: ``` import React from 'react'; import { KeepAliveProvider, KeepAlive } from './keep-alive'; function App() { return ( <KeepAliveProvider> <div> <h1>My App</h1> <KeepAlive> <MyComponent /> </KeepAlive> </div> </KeepAliveProvider> ); } function MyComponent() { // ... } export default App; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值