2 problems with Component

  1. As long as setState() is executed, even if the state data is not changed, the component will re-render() ==> Inefficient
  2. Only the current component re-render(), it will automatically re-render the child component, even if the child component does not use any data of the parent component ==> low efficiency

Efficient approach

Re-render() only when the component's state or props data changes

the reason

ShouldComponentUpdate() in Component always returns true

solve

办法1: 
    重写shouldComponentUpdate()方法
    比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false
办法2:  
    使用PureComponent
    PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true
注意: 
    只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false  
    不要直接修改state数据, 而是要产生新数据(对象或者数组的时候可以使用扩展运算符)
    
项目中一般使用PureComponent来优化

Example:

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>
    )
  }
}

万年打野易大师
1.5k 声望1.1k 粉丝