react類組件優化

Component的2個問題

  1. 只要執行setState(),即便不改變狀態數據, 組件也會從新render() ==> 效率低
  2. 只當前組件從新render(), 就會自動從新render子組件,縱使子組件沒有用到父組件的任何數據 ==> 效率低

效率高的作法

只有當組件的state或props數據發生改變時才從新render()css

緣由

Component中的shouldComponentUpdate()老是返回truereact

解決

辦法1: 
    重寫shouldComponentUpdate()方法
    比較新舊state或props數據, 若是有變化才返回true, 若是沒有返回false
辦法2:  
    使用PureComponent
    PureComponent重寫了shouldComponentUpdate(), 只有state或props數據有變化才返回true
注意: 
    只是進行state和props數據的淺比較, 若是隻是數據對象內部數據變了, 返回false  
    不要直接修改state數據, 而是要產生新數據(對象或者數組的時候能夠使用擴展運算符)
    
項目中通常使用PureComponent來優化

示例:數組

import React, { PureComponent } from 'react'
import './index.css'

export default class Parent extends PureComponent {
  state = { carName: '奔馳c36', stus: ['小張', '小李', '小王'] }

  addStu = () => {
    /* const {stus} = this.state
       stus.unshift('小劉')
       this.setState({stus}) */

    const { stus } = this.state
    this.setState({ stus: ['小劉', ...stus] })
  }

  changeCar = () => {
    //this.setState({carName:'邁巴赫'})

    const obj = this.state
    obj.carName = '邁巴赫'
    console.log(obj === this.state)
    this.setState(obj)
  }

  /* shouldComponentUpdate(nextProps,nextState){
     console.log(this.props,this.state); //目前的props和state
     console.log(nextProps,nextState); //接下要變化的目標props,目標state
     return !this.state.carName === nextState.carName
  } */

  render() {
    console.log('Parent---render')
    const { carName } = this.state
    return (
      <div className="parent">
        <h3>我是Parent組件</h3>
        {this.state.stus}&nbsp;
        <span>個人車名字是:{carName}</span>
        <br />
        <button onClick={this.changeCar}>點我換車</button>
        <button onClick={this.addStu}>添加一個小劉</button>
        <Child carName="奧拓" />
      </div>
    )
  }
}

class Child extends PureComponent {
  /* shouldComponentUpdate(nextProps,nextState){
     console.log(this.props,this.state); //目前的props和state
     console.log(nextProps,nextState); //接下要變化的目標props,目標state
     return !this.props.carName === nextProps.carName
  } */

  render() {
    console.log('Child---render')
    return (
      <div className="child">
        <h3>我是Child組件</h3>
        <span>我接到的車是:{this.props.carName}</span>
      </div>
    )
  }
}
相關文章
相關標籤/搜索