react中类组件的相关问题及优化

1、Component的2个问题

  1. 只要执行setState(),即使不改变状态数据, 组件也会重新render() ==> 效率低

  2. 只当前组件重新render(), 就会自动重新render子组件,纵使子组件没有用到父组件的任何数据 ==> 效率低

示例代码:

import React, {Component} from 'react';

export default class Parent extends Component {
    state = {carName: "奔驰"}
    changeCar = () => {
        this.setState({carName: "迈巴赫"})
    }

    render() {
        console.log("parent----render");
        return (
            <div style={{backgroundColor: "red", padding: "0 20px"}}>
                <h1>我是father组件</h1>
                <p>我的车是:{this.state.carName}</p>
                <button onClick={this.changeCar}>点我换车</button>
                <Child carName={this.state.carName}/>
            </div>
        )
    }
}

class Child extends Component {
    render() {
        console.log("render----child");

        return (
            <div style={{backgroundColor: "gray"}}>
                <h3>我是child组件</h3>
                <p>我接收到的车是:{this.props.carName}</p>
            </div>
        )
    }
}

2、效率高的方法:

  只有当组件的state或props数据发生改变时才重新render();

3、原因

  Component中的shouldComponentUpdate()总是返回true;

  shouldComponentUpdate()用于控制组件是否更新的阀门;

  链接: react的生命周期

4、解决方法

4.1、方法1:

  重写shouldComponentUpdate()方法;

  比较新旧state或props数据, 如果有变化才返回true, 如果没有返回false;

/*可以接收三个参数:
    *   1、nextProps
    *   2、nextState
    *   3、nextContext
    * */
    shouldComponentUpdate(nextProps, nextState, nextContext) {
        console.log(this.props, this.state);//目前的props,和state
        console.log(nextProps, nextState);//接下来要变化的目标props,state
        if (this.state.carName === nextState.carName) return false
        else return true
    }
shouldComponentUpdate(nextProps, nextState, nextContext) {
        console.log(this.props, this.state);//目前的props,和state
        console.log(nextProps, nextState);//接下来要变化的目标props,state
        return !this.props.carName === nextProps.carName
    }

4.2、方法2:

  使用PureComponent,PureComponent重写了shouldComponentUpdate(), 只有state或props数据有变化才返回true

export default class Parent extends PureComponent{
}

class Child extends PureComponent {
}

注意:
只是进行state和props数据的浅比较, 如果只是数据对象内部数据变了, 返回false ,不要直接修改state数据, 而是要产生新数据。项目中一般使用PureComponent来优化。

直接修改数据,没有产生新数据,组件不会重新渲染,state不会更新
        const obj = this.state;
        obj.carName = "迈巴赫";
        console.log(obj === this.state);//true
        this.setState(obj)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值