痛点

移动端开发时会遇到在列表页点击进入详情,返回后列表页刷新的情况,对用户体验很不友好。
在这里插入图片描述

解决方案:react-router-cache-route实现页面状态的缓存

版本

    "react": "^17.0.2",
    "react-router-cache-route": "^1.11.1",

用法

// 1.安装插件
npm install react-router-cache-route --save

思路:就是把Switch替换成CacheSwitch,因为因为Switch组件只保留第一个匹配状态的路由,卸载掉其他路由
把Route替换成CacheRoute

详细例子

1.配置路由

官网例子

import React from 'react'
import { HashRouter as Router, Route } from 'react-router-dom'
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'
import List from './views/List'
import Item from './views/Item'
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>
)
export default App

2.修改缓存页面的部分内容-didRecover

需求:移动端,在列表页通过底部导航跳转到首页,底部导航选中首页,此时跳转到列表页,底部导航没有选中列表页。

解决方案:使用didRecover

import BottomNav from '../../components/BottomNav/BottomNav'

constructor(props) {
  super(props);
  this.state = {
    showBotNav: true,
  }
  props.cacheLifecycles.didRecover(this.componentDidRecover)
}

componentDidRecover = () => {
  // 控制底部导航的显示
  this.setState({showBotNav: !this.state.showBotNav});
  setTimeout(()=>{ this.setState({showBotNav: !this.state.showBotNav}) }, 1)
}

至此已处理完毕,如果帮你出坑了,请打赏几毛钱在这里插入图片描述在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐