当前位置: 首页 > news >正文

React 中实现 vue keep-alive 功能的方法

1. 使用 React Router 的 React.lazy 和 Suspense

React Router 的 React.lazy 和 Suspense 可以用于动态加载组件,并且可以结合 React.memo 或自定义的缓存逻辑来实现类似 keep-alive 的功能。

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));function App() {return (<Router><Suspense fallback={<div>Loading...</div>}><Switch><Route exact path="/" component={Home} /><Route path="/about" component={About} /></Switch></Suspense></Router>);
}export default App;

2. 使用自定义的 Higher-Order Component (HOC)

import React, { Component } from 'react';const withCache = (WrappedComponent) => {class CacheComponent extends Component {constructor(props) {super(props);this.cachedInstance = null;}componentDidMount() {this.cachedInstance = <WrappedComponent {...this.props} />;}componentDidUpdate(prevProps) {if (prevProps.key !== this.props.key) {this.cachedInstance = <WrappedComponent {...this.props} />;}}render() {return this.cachedInstance;}}return CacheComponent;
};const Home = (props) => (<div><h1>Home Page</h1><p>{props.message}</p></div>
);const CachedHome = withCache(Home);function App() {const [message, setMessage] = React.useState('Welcome to the Home Page');return (<div><button onClick={() => setMessage('New Message')}>Change Message</button><CachedHome message={message} key={message} /></div>);
}export default App;

3. 使用 React Context 和自定义 Hook

import React, { createContext, useContext, useState, useEffect } from 'react';const CacheContext = createContext();const CacheProvider = ({ children }) => {const [cache, setCache] = useState({});const addToCache = (key, component) => {setCache((prevCache) => ({...prevCache,[key]: component}));};const getCachedComponent = (key) => {return cache[key];};return (<CacheContext.Provider value={{ addToCache, getCachedComponent }}>{children}</CacheContext.Provider>);
};const useCache = () => {const context = useContext(CacheContext);if (!context) {throw new Error('useCache must be used within a CacheProvider');}return context;
};const withCache = (WrappedComponent) => {return (props) => {const { addToCache, getCachedComponent } = useCache();const key = props.key || 'default';useEffect(() => {const cachedComponent = getCachedComponent(key);if (!cachedComponent) {const component = <WrappedComponent {...props} />;addToCache(key, component);}}, [key, props, addToCache, getCachedComponent]);return getCachedComponent(key);};
};const Home = (props) => (<div><h1>Home Page</h1><p>{props.message}</p></div>
);const CachedHome = withCache(Home);function App() {const [message, setMessage] = React.useState('Welcome to the Home Page');return (<CacheProvider><div><button onClick={() => setMessage('New Message')}>Change Message</button><CachedHome message={message} key={message} /></div></CacheProvider>);
}export default App;

4. 使用第三方库

有一些第三方库可以帮助实现类似 keep-alive 的功能,例如 react-keep-alive。

npm install react-keep-alive
import React from 'react';
import { KeepAlive, AliveScope } from 'react-keep-alive';const Home = (props) => (<div><h1>Home Page</h1><p>{props.message}</p></div>
);function App() {const [message, setMessage] = React.useState('Welcome to the Home Page');return (<AliveScope><div><button onClick={() => setMessage('New Message')}>Change Message</button><KeepAlive name="home"><Home message={message} /></KeepAlive></div></AliveScope>);
}export default App;

http://www.mrgr.cn/news/35111.html

相关文章:

  • web群集--rocky9.2部署zabbix服务端的详细过程
  • 如何使用ECharts制作折线图
  • 用于体积医学图像分割的跨视角差异依赖网络|文献速递--基于多模态-半监督深度学习的病理学诊断与病灶分割
  • 软件验收测试报告有什么作用?第三方验收测试报告包括哪些内容?
  • EasyCVR全方位安全守护智慧电厂:构建高效视频监控系统优势分析
  • 【源码】Sharding-JDBC源码分析之ShardingSphereConnection的创建原理
  • 分享C++程序员面试八股文(九)
  • 《动手学深度学习》笔记2.1——神经网络从基础→进阶 (模型构建→参数初始化→设计层/块→磁盘读写→多GPU加速)
  • RPC框架开发——理解项目功能
  • 可看见车辆行人的高清实时视频第2辑
  • unity CustomEditor的基本使用
  • vue强制刷新组件的三种方式:$forceupdate、v-if、key
  • Spring Boot 学习之路 -- 处理 HTTP 请求
  • 基于深度学习的花卉智能分类识别系统
  • 仿黑神话悟空跑动-脚下波纹特效(键盘wasd控制走动)
  • 五种方式帮你提升独立站销售额
  • Frp经常连接不上?查看Frp常见问题排查
  • SSM+Vue共享单车管理系统
  • 分布式光伏监控系统 在鄂尔多斯市鄂托克旗某煤矿项目中的应用
  • 电路 - 笔记2