关于react.js:react类组件优化

Component的2个问题

  1. 只有执行setState(),即便不扭转状态数据, 组件也会从新render() ==> 效率低
  2. 只以后组件从新render(), 就会主动从新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低

效率高的做法

只有当组件的state或props数据产生扭转时才从新render()

起因

Component中的shouldComponentUpdate()总是返回true

解决

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理