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

1次阅读

共计 1742 个字符,预计需要花费 5 分钟才能阅读完成。

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>
    )
  }
}
正文完
 0