React的学习过程中记录的知识点-----路由切换的性能问题

在这里插入图片描述
1.0 state的改变以 及 props的改变 都会导致组件的重新渲染,所以要考虑性能问题,充分利用导航钩子

2.0 路由的编程式导航( this.props.localtion.push),或者 <Link > 的方式进行路由切换的动作,都会导致对应的组件创建,渲染,销毁等行为,比较消耗性能,如果是同一路由多次点击,应该要做一个判断,是同一路由下就不做路由切换动作,提高性能,实习思路就是在当前嵌套路由的最外层的组件的 componentDidUpdate 钩子中将当前路由存储起来,当再次点击的时候进行对比,如果还是同一个路由,那么就不进行路由的切换动作(即编程式导航)

 // Home组件实现代码如下
 import React, { Component } from 'react'
// 导入路由
import { Route } from 'react-router-dom'

// 导入子组件
import Index from '../Index'
import HouseLists from '../HouseLists'
import News from '../News'
import Profile from '../Profile'

// 按需导入anted-mobile的组件
import { TabBar } from 'antd-mobile'

// 模块化导入样式
import style from './index.module.scss'

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedTab: props.location.pathname
    }
  }
  // tabs数组
  TABS = [
    {
      title: '首页',
      icon: 'icon-index',
      path: '/home'
    },
    {
      title: '找房',
      icon: 'icon-findHouse',
      path: '/home/list'
    },
    {
      title: '资讯',
      icon: 'icon-info',
      path: '/home/news'
    },
    {
      title: '我的',
      icon: 'icon-my',
      path: '/home/profile'
    }
  ]

  // 渲染 TabBar
  renderTabBar = () => {
    return (
      <TabBar tintColor="#21B97A" noRenderContent>
        {this.TABS.map(item => {
          return (
            <TabBar.Item
              icon={<i className={`iconfont ${item.icon}`}></i>}
              selectedIcon={<i className={`iconfont ${item.icon}`}></i>}
              title={item.title}
              key={item.path}
              selected={this.state.selectedTab === item.path}
              onPress={() => {
                // this.setState({
                //   selectedTab: item.path
                // })
                // 通过编程式导航实现路由切换
                if (this.props.location.pathname !== item.path) {
                  this.props.history.push(item.path)
                }
              }}
            ></TabBar.Item>
          )
        })}
      </TabBar>
    )
  }

  // 方式二: 通过钩子,判断两次点击的是否为同一路由,同一路由,就不必修改 state中的值,因为修改了会从新渲染,很消耗性能
  componentDidUpdate(preProps) {
    if (preProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        selectedTab: this.props.location.pathname
      }) 
    }
  }
  render() {
    return (
      <div className={style.home}>
        {/* Route 占位以及路由匹配 */}
        <Route exact path="/home" component={Index} />
        <Route path="/home/list" component={HouseLists} />
        <Route path="/home/news" component={News} />
        <Route path="/home/profile" component={Profile} />
        <div className={style.tabbar}>{this.renderTabBar()}</div>
      </div>
    )
  }
}
export default Home

发布了102 篇原创文章 · 获赞 14 · 访问量 7068

猜你喜欢

转载自blog.csdn.net/weixin_42060658/article/details/104353495
今日推荐