【React】实现类似vue的keepAlive组件的持久化

【React】实现类似vue的keepAlive组件的持久化

1. 创建 KeepAliveContext.js

首先,我们需要创建一个 KeepAliveContext 来存储需要持久化的组件实例。

// src/KeepAliveContext.js
import { createContext, useState } from "react"

export const KeepAliveContext = createContext()

function KeepAliveProvider(props) {
  /**
   * {
   *   home: {
   *      id: 'home',
   *      element: element,
   *      nodes: nodes,
   *   },
   *   user: {
   *      id: 'user',
   *      element: element,
   *      nodes: nodes,
   *   }
   * }
   */
  const [cached, setCached] = useState({})

  return (
    <KeepAliveContext.Provider value={{ cached, setCached }}>
      {props.children}
      {Object.values(cached).map(({ id, element, nodes }) => (
        <div
          key={id}
          ref={(node) => {
            if (node && !nodes) {
              // 缓存实例的 childNodes
              setCached({
                ...cached,
                [id]: { id, element, nodes: [...node.childNodes] }
              })
            }
          }}
        >
          {element}
        </div>
      ))}
    </KeepAliveContext.Provider>
  )
}

export default KeepAliveProvider

2. 创建 keepAlive.js

接下来,我们创建 keepAlive 函数,该函数负责缓存组件的实例。

// src/KeepAlive.js
/* eslint-disable react-hooks/rules-of-hooks */
import { useContext, useEffect, useRef } from "react"
import { KeepAliveContext } from "./KeepAliveContext"

export default function KeepAlive(KeepAliveComponent, id) {
  return function (props) {
    const _ref = useRef(null)
    const { cached, setCached } = useContext(KeepAliveContext)
    useEffect(() => {
      if (!cached[id]) {
        // 首次初始化时缓存组件实例
        setCached({
          ...cached,
          [id]: { id, element: <KeepAliveComponent {...props} />, nodes: null }
        })
      } else {
        const { nodes } = cached[id]
        if (nodes && Array.isArray(nodes)) {
          nodes.forEach((node) => _ref.current.appendChild(node))
        }
      }
    }, [cached, setCached, props])
    return <div ref={_ref}></div>
  }
}

3. 创建示例组件 Counter.js

这是一个简单的计数器组件,用于测试 KeepAlive 功能。

// src/components/Counter.js
import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default Counter;

4. 创建应用主组件 App.js

在这个主组件中,我们使用 KeepAliveProviderkeepAlive 函数来管理组件的持久化。

// src/App.js
import React, { useState } from 'react';
import { KeepAliveProvider } from './KeepAliveContext';
import keepAlive from './keepAlive';
import Counter from './components/Counter';

const AliveCounter = keepAlive('counter', Counter);

const App = () => {
  const [showCounter, setShowCounter] = useState(true);

  return (
    <KeepAliveProvider>
      <div>
        <button onClick={() => setShowCounter(!showCounter)}>
          {showCounter ? 'Hide' : 'Show'} Counter
        </button>
        {showCounter && <AliveCounter />}
      </div>
    </KeepAliveProvider>
  );
};

export default App;

5. 入口文件 index.js

确保在你的入口文件中正确引入 App 组件并渲染它。

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

总结

通过这个完整的案例,我们实现了一个类似于 Vue 的 KeepAlive 功能的组件,通过缓存组件的实例和其 childNodes,在重新渲染时通过读取childNodes恢复组件。通过这种方式,我们可以确保组件的实际 DOM 节点在卸载和重新挂载之间保持不变,从而实现了组件的持久化。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中没有内置的TabPane组件缓存功能类似Vuekeep-alive。但是我们可以通过以下方法来实现类似的缓存效果。 一种方法是利用React的状态管理机制,结合条件渲染来实现TabPane的缓存。具体步骤如下: 1. 在TabPane组件的父组件中,创建一个状态变量用于标识当前选择的Tab。 2. 在TabPane组件中,根据该状态变量的值来决定是否渲染该Tab内容。 3. 当切换Tab时,只修改状态变量的值而不重新渲染TabPane组件,以达到缓存的效果。 示例代码如下: ```jsx import React, { useState } from 'react'; const App = () => { const [currentTab, setCurrentTab] = useState(0); const handleTabChange = (index) => { setCurrentTab(index); }; return ( <div> <ul> <li onClick={() => handleTabChange(0)}>Tab 1</li> <li onClick={() => handleTabChange(1)}>Tab 2</li> <li onClick={() => handleTabChange(2)}>Tab 3</li> </ul> <div> {currentTab === 0 && <TabContent1 />} {currentTab === 1 && <TabContent2 />} {currentTab === 2 && <TabContent3 />} </div> </div> ); }; const TabContent1 = () => { return <div>Tab 1 Content</div>; }; const TabContent2 = () => { return <div>Tab 2 Content</div>; }; const TabContent3 = () => { return <div>Tab 3 Content</div>; }; export default App; ``` 通过上述方法,只有当前选择的Tab内容会被渲染,而其他Tab的内容则会被缓存,达到类似Vuekeep-alive的效果。 另外,还可以使用第三方库如`react-tabs`或`react-router`等来实现类似的Tab缓存功能,这些库提供了更丰富的Tab组件并且内置了缓存功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值