轉載---官方文檔:https://github.com/CJY0208/react-router-cache-route/blob/master/README_CN.md
CacheRoute
搭配 react-router
工作的、帶緩存功能的路由組件,類似於 Vue
中的 keep-alive
功能
React v15+
React-Router v4+
遇到的問題
使用 Route
時,路由對應的組件在前進或后退無法被緩存,導致了 數據和行為的丟失
例如:列表頁滾動到底部后,點擊跳轉到詳情頁,返回后會回到列表頁頂部,丟失了滾動位置和數據的記錄
原因 & 解決方案
Route
中配置的組件在路徑不匹配時會被卸載(render 方法中 return null),對應的真實節點也將從 dom 樹中刪除
在閱讀了 Route
的源碼后我們發現可以將 children
當作方法來使用,以幫助我們手動控制渲染的行為
隱藏替代刪除 可以解決遇到的問題
安裝
npm install react-router-cache-route --save
使用方法
可以使用 CacheRoute
組件的 component
, render
, children
屬性裝載組件
注意:緩存語句不要寫在 Switch
組件當中,因為 Switch
組件會卸載掉所有非匹配狀態下的路由,需使用 CacheSwitch
替代 Switch
使用 when
屬性決定何時使用緩存功能,可選值為 [forward
, back
, always
] ,默認值為 forward
使用 className
屬性給包裹組件添加自定義樣式
也可以使用 behavior
屬性來自定義緩存狀態下組件的隱藏方式,工作方式是根據 CacheRoute
當前的緩存狀態,返回一個作用於包裹組件的 props
import React from 'react' import { HashRouter as Router, Switch, Route } from 'react-router-dom' import CacheRoute, { CacheSwitch } from 'react-router-cache-route' import List from './components/List' import Item from './components/Item' import List2 from './components/List2' import Item2 from './components/Item2' const App = () => ( <Router> {/* 也可使用 render, children prop <CacheRoute exact path="/list" render={props => <List {...props} />} /> 或 <CacheRoute exact path="/list"> {props => <List {...props} />} </CacheRoute> 或 <CacheRoute exact path="/list"> <div> 支持多個子組件 </div> <List /> </CacheRoute> */} <CacheRoute exact path="/list" component={List} when="always" /> <Switch> <Route exact path="/item/:id" component={Item} /> </Switch> <CacheSwitch> <CacheRoute exact path="/list2" component={List2} className="custom-style" behavior={cached => (cached ? { style: { position: 'absolute', zIndex: -9999, opacity: 0, visibility: 'hidden', pointerEvents: 'none' }, className: '__CacheRoute__wrapper__cached' } : { className: '__CacheRoute__wrapper__uncached' })} /> <Route exact path="/item2/:id" component={Item2} /> <Route render={() => ( <div>404 未找到頁面</div> )} /> </CacheSwitch> </Router> ) export default App
額外的生命周期
使用 CacheRoute
的組件將會得到一個名為 cacheLifecycles
的屬性,里面包含兩個額外生命周期的注入函數 didCache
和 didRecover
,分別用在組件 被緩存 和 被恢復 時
import React, { Component } from 'react' export default class List extends Component { constructor(props, ...args) { super(props, ...args) props.cacheLifecycles.didCache(this.componentDidCache) props.cacheLifecycles.didRecover(this.componentDidRecover) } componentDidCache = () => { console.log('List cached') } componentDidRecover = () => { console.log('List recovered') } render() { return ( // ... ) } }
手動清除緩存
使用 cacheKey
prop 和 dropByCacheKey
函數來手動控制緩存
import CacheRoute, { dropByCacheKey, getCachingKeys } from 'react-router-cache-route' ... <CacheRoute ... cacheKey="MyComponent" /> ... console.log(getCachingKeys()) // 如果 `cacheKey` prop 為 'MyComponent' 的緩存路由已處於緩存狀態,將得到 ['MyComponent'] ... dropByCacheKey('MyComponent') ...