{"id":13504425,"url":"https://github.com/GoodLuckAlien/react-keepalive-router","last_synced_at":"2025-03-29T21:30:37.457Z","repository":{"id":41271330,"uuid":"314441297","full_name":"GoodLuckAlien/react-keepalive-router","owner":"GoodLuckAlien","description":"The react cache component developed based on react 16.8 +, react router 4 + can be used to cache page components, similar to Vue keepalive package Vue router effect function.(基于react 16.8+ ,react-router 4+ 开发的react缓存组件，可以用于缓存页面组件，类似vue的keepalive包裹vue-router的效果功能)。","archived":false,"fork":false,"pushed_at":"2023-08-02T12:50:03.000Z","size":11681,"stargazers_count":653,"open_issues_count":7,"forks_count":56,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-03-18T13:09:11.836Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GoodLuckAlien.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-11-20T03:56:06.000Z","updated_at":"2025-02-14T09:34:21.000Z","dependencies_parsed_at":"2024-01-13T19:20:00.637Z","dependency_job_id":"eb9f44a0-96ba-4711-8502-bfb7438678c2","html_url":"https://github.com/GoodLuckAlien/react-keepalive-router","commit_stats":null,"previous_names":["alienzhaolin/react-keepalive-router"],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoodLuckAlien%2Freact-keepalive-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoodLuckAlien%2Freact-keepalive-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoodLuckAlien%2Freact-keepalive-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoodLuckAlien%2Freact-keepalive-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GoodLuckAlien","download_url":"https://codeload.github.com/GoodLuckAlien/react-keepalive-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246249136,"owners_count":20747165,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T00:00:37.565Z","updated_at":"2025-03-29T21:30:35.376Z","avatar_url":"https://github.com/GoodLuckAlien.png","language":"JavaScript","funding_links":[],"categories":["Utilities","JavaScript"],"sub_categories":["Router"],"readme":"\n\n[![npm version](https://img.shields.io/npm/v/react-keepalive-router.svg?style=flat-square)](https://www.npmjs.org/package/react-keepalive-router)\n[![NPM Downloads](https://badgen.net/npm/dm/react-keepalive-router)](https://npmjs.org/package/react-keepalive-router)\n![](https://img.shields.io/github/stars/GoodLuckAlien/react-keepalive-router.svg?style=social\u0026label=Star)\n\n# react-keepalive-router\n\n\n## 一 介绍\n\n基于`react 16.8+` ,`react-router 4+` 开发的`react`缓存组件，可以用于缓存页面组件，类似`vue`的`keepalive`包裹`vue-router`的效果功能。\n\n采用`react hooks`全新`api`,支持缓存路由，手动解除缓存，增加了**缓存的状态周期**，监听函数等。\n\n后续版本会完善其他功能。\n\n\n\n### demo\n\n#### 缓存组件 + 监听\n\n\n## 二 快速上手\n\n\n### 下载\n\n```bash\nnpm install react-keepalive-router --save\n# or\nyarn add react-keepalive-router\n```\n\n\n### 使用\n\n### 1 基本用法\n\n\n#### KeepaliveRouterSwitch\n\n\n`KeepaliveRouterSwitch`可以理解为常规的Switch,也可以理解为 `keepaliveScope`,我们**确保整个缓存作用域，只有一个 `KeepaliveRouterSwitch` 就可以了**。\n\n#### 常规用法\n\n````jsx\nimport { BrowserRouter as Router, Route, Redirect ,useHistory  } from 'react-router-dom'\nimport { KeepaliveRouterSwitch ,KeepaliveRoute ,addKeeperListener } from 'react-keepalive-router'\n\nconst index = () =\u003e {\n  useEffect(()=\u003e{\n    /* 增加缓存监听器 */\n    addKeeperListener((history,cacheKey)=\u003e{\n      if(history)console.log('当前激活状态缓存组件：'+ cacheKey )\n    })\n  },[])\n  return \u003cdiv \u003e\n    \u003cdiv \u003e\n      \u003cRouter  \u003e\n      \u003cMeuns/\u003e\n      \u003cKeepaliveRouterSwitch\u003e\n          \u003cRoute path={'/index'} component={Index} \u003e\u003c/Route\u003e\n          \u003cRoute path={'/list'} component={List} \u003e\u003c/Route\u003e\n          { /* 我们将详情页加入缓存 */ }\n          \u003cKeepaliveRoute path={'/detail'} component={ Detail } \u003e\u003c/KeepaliveRoute\u003e\n          \u003cRedirect from='/*' to='/index' /\u003e\n       \u003c/KeepaliveRouterSwitch\u003e\n      \u003c/Router\u003e\n    \u003c/div\u003e\n  \u003c/div\u003e\n}\n````\n\n\n这里应该注意⚠️的是对于复杂的路由结构。或者KeepaliveRouterSwitch 包裹的子组件不是Route ,我们要给 `KeepaliveRouterSwitch` 增加特有的属性 `withoutRoute` 就可以了。如下例子🌰🌰🌰：\n\n**例子一**\n\n````jsx\n\u003cKeepaliveRouterSwitch withoutRoute \u003e\n  \u003cdiv\u003e\n     \u003cRoute path=\"/a\" component={ComponentA}  /\u003e\n     \u003cRoute path=\"/b\" component={ComponentB}  /\u003e\n     \u003cKeepaliveRoute path={'/detail'} component={ Detail } \u003e\u003c/KeepaliveRoute\u003e\n  \u003c/div\u003e\n\u003c/KeepaliveRouterSwitch\u003e\n\n````\n\n**例子二**\n\n或者我们可以使用 `renderRoutes` 等`api`配合 `KeepliveRouterSwitch` 使用 。\n\n````jsx\nimport {renderRoutes} from \"react-router-config\"\n\u003cKeepliveRouterSwitch withoutRoute  \u003e{ renderRoutes(routes) }\u003c/KeepliveRouterSwitch\u003e \n````\n\n\n#### KeepaliveRoute\n\n`KeepaliveRoute` 基本使用和 `Route`没有任何区别。\n\n\n**在当前版本中⚠️⚠️⚠️如果 `KeepaliveRoute` 如果没有被 `KeepaliveRouterSwitch`包裹就会失去缓存作用。**\n\n**效果**\n\n![demo演示](https://raw.githubusercontent.com/AlienZhaolin/react-keepalive-router/master/md/111.gif)\n\n\n![demo演示1](https://raw.githubusercontent.com/AlienZhaolin/react-keepalive-router/master/md/form.gif)\n\n### 2 其他功能\n\n\n\n#### 1 缓存组件激活监听器\n\n如果我们希望对当前激活的组件，有一些额外的操作，我们可以添加监听器，用来监听缓存组件的激活状态。\n\n````js\naddKeeperListener((history,cacheKey)=\u003e{\n  if(history)console.log('当前激活状态缓存组件：'+ cacheKey )\n})\n````\n第一个参数未history对象，第二个参数为当前缓存路由的唯一标识cacheKey\n\n#### 2 清除缓存\n\n缓存的组件，或是被`route`包裹的组件，会在`props`增加额外的方法`cacheDispatch`用来清除缓存。\n\n如果props没有`cacheDispatch`方法，可以通过\n\n\n````js\n\n\nimport React from 'react'\nimport { useCacheDispatch } from 'react-keepalive-router'\n\nfunction index(){\n    const cacheDispatch = useCacheDispatch()\n    return \u003cdiv\u003e我是首页\n        \u003cbutton onClick={()=\u003e cacheDispatch({ type:'reset' }) } \u003e清除缓存\u003c/button\u003e\n    \u003c/div\u003e\n}\n\nexport default index\n````\n\n**1 清除所有缓存**\n\n````js\ncacheDispatch({ type:'reset' }) \n````\n\n**2 清除单个缓存**\n\n````js\ncacheDispatch({ type:'reset',payload:'cacheId' }) \n````\n\n**3 清除多个缓存**\n\n````js\ncacheDispatch({ type:'reset',payload:['cacheId1'，'cacheId2'] }) \n````\n\n#### 3 缓存scroll ，增加缓存滚动条功能\n\n如果我们想要缓存列表 `scrollTop` 的位置 ,我们可以在 `KeepaliveRoute` 动态添加 `scroll` 属性 ( 目前仅支持y轴 )。 为什么加入`scroll`，我们这里考虑到，只有在想要缓存`scroll`的y值的时候，才进行缓存，避免不必要的事件监听和内存开销。\n\n````js\n \u003cKeepaliveRoute path={'/list2'} component={List2} scroll /\u003e\n````\n\n**效果**\n\n![scroll demo演示](https://raw.githubusercontent.com/AlienZhaolin/react-keepalive-router/master/md/scroll.gif)\n\n\n\n#### 4 生命周期\n\n`react-keepalive-router`加入了全新的页面组件生命周期 `actived` 和 `unActived`, `actived` 作为缓存路由组件激活时候用，初始化的时候会默认执行一次 ,  `unActived`作为路由组件缓存完成后调用。但是生命周期需要用一个`HOC`组件`keepaliveLifeCycle`包裹。\n\n使用：\n\n\n\n\n````js\nimport React   from 'react'\n\nimport { keepaliveLifeCycle } from 'react-keepalive-router'\nimport './style.scss'\n\n@keepaliveLifeCycle\nclass index extends React.Component\u003cany,any\u003e{   \n    \n    state={\n        activedNumber:0,\n        unActivedNumber:0\n    }\n    actived(){\n        this.setState({\n            activedNumber:this.state.activedNumber + 1\n        })\n    }\n    unActived(){\n        this.setState({\n            unActivedNumber:this.state.unActivedNumber + 1\n        })\n    }\n    render(){\n        const { activedNumber , unActivedNumber } = this.state\n        return \u003cdiv  style={ { marginTop :'50px' } }  \u003e\n           \u003cdiv\u003e 页面 actived 次数： { activedNumber } \u003c/div\u003e\n           \u003cdiv\u003e 页面 unActived 次数：{ unActivedNumber  } \u003c/div\u003e\n        \u003c/div\u003e\n    }\n}\n\nexport default index\n````\n\n效果：\n\n\n![lifecycle demo演示](https://raw.githubusercontent.com/AlienZhaolin/react-keepalive-router/master/md/lifecycle.gif)\n\n这里注意的是 `keepaliveLifeCycle` 要是组件最近的 `Hoc`。\n\n比如 \n\n装饰器模式下：\n**🙅错误做法**\n````js\n@keepaliveLifeCycle\n@withStyles(styles)\n@withRouter\nclass Index extends React.Componen{\n   \n}\n````\n\n**🙆正确做法**\n````js\n@withStyles(styles)\n@withRouter\n@keepaliveLifeCycle\nclass Index extends React.Componen{\n   \n}\n````\n\n非装饰器模式下：\n**🙅错误做法**\n````js\nclass Index extends React.Componen{\n\n}\n\nexport default keepaliveLifeCycle( withRouter(Index) )\n````\n\n**🙆正确做法**\n````js\nclass Index extends React.Componen{\n   \n}\n\nexport default withRouter( keepaliveLifeCycle(Index) )\n````","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGoodLuckAlien%2Freact-keepalive-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGoodLuckAlien%2Freact-keepalive-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGoodLuckAlien%2Freact-keepalive-router/lists"}