主要業務場景就是列表頁跳轉到詳情頁中,再回到列表頁中,列表頁還是保持之前的狀態 比如:分頁,搜索條件
網上搜索大概有幾種方法:
1. 使用localStorage/sessionStorage進行頁面的狀態的保存,跳轉頁面后再進行獲取,這種方法雖然可行,但是從根本來說還是從新向后台再一次請求了數據,不算最佳方案。
2. react-kepper,需要將項目的react-router替換掉,風險較大,慎用
3. react-router-cache-route,簡單易用,最佳方案
最后采用的第三種
基本使用方法:
就是把Switch替換成CacheSwitch,因為因為Switch組件只保留第一個匹配狀態的路由,卸載掉其他路由把Route替換成CacheRoute
注意:詳情頁面回退列表頁時使用this.props.history.push('路徑')可以實現頁面的緩存
但當使用this.props.history.go(-1)則有可能緩存失敗
1. 安裝
npm install react-router-cache-route --save / yarn add react-router-cache-route
2. 引入
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'
3. 示例
const App = () => (
<Router>
<CacheSwitch>
<CacheRoute exact path="/list" component={List} />
<Route exact path="/item/:id" component={Item} />
<Route render={() => <div>404 Not Found</div>} />
</CacheSwitch>
</Router>
)
4. 注意
//解決緩存頁面中的bug (菜單異常) 會出現監聽不到路由
//給CacheRoute增加屬性when 屬性值為true false
//配置路由demo.js文件中
{ client_type: 2, name: '設備管理', path: '/web/monitor/device', cacheRoute: true, applyRouteName:['/web/monitor/device2/readDevice'] }
//增加applyRouteName屬性 值為:這個路由中的子路由地址
const whenFunction = (applyRouteName) => {
return () => applyRouteName!==undefined && applyRouteName.includes(window.location.pathname)
}
<CacheRoute path={item.path} key={item.path} cacheKey={"MyComponent"} exact when={whenFunction(item.applyRouteName)} render={route => ( <BaseView key={idx} {...route} handleHeader={handleHeader} handleSlider={handleSlider} listenRouterPath={listenRouterPath} > <Components {...route} /> </BaseView> )} />