React学习day21——组件优化Component

Component

Component的2个问题
1、只要执行setState(),即使不改变状态数据,组件也会重新render()==>效率低
2、每当前组件重新render(),就会重新render子组件,纵使子组件没有到父组件的任何数据 ==>效率低

效率高的做法
只有当组件的state 或 props数据发生改变时才重新render()
原因
Component中的shouldComponentUpdate()总是返回true
解决
方法1:
重写shouldComponentUpdate()方法
比较新旧state或props数据,如果有变化才返回true,如果没有返回false
方法2:
使用PureComponent
PureComponent重写了shouldCompoentUpdate(),只要state或props数据有变化才返回true
注意:
只是进行state和props数据的浅比较,如果只是数据对象内部数据变了,返回false
不要直接修改state数据,而是产生新数据
项目中一般使用PureComponent来优化

import React, {Component} from 'react';
import './index.css'
export default class Parent extends Component {
    state = {carName:'奔驰'}
    changeCar = ()=>{
       this.setState({carName:'劳斯莱斯'})
    }
    shouldComponentUpdate(nextPros,nextState){
        console.log(this.props,this.state)
        console.log(nextPros,nextState)
        if(this.props.carName === nextState.carName){
            return false
        }
         else return true

    }
    render() {
        return (
            <div className="parent">
                <h2>我是Parent组件</h2>
                <span>我的车名是:{this.state.carName}</span>

                <button onClick={this.changeCar}>升级</button>
                <Child carName={this.state.carName}/>
            </div>
        );
    }
}
class  Child extends  Component{
    render() {
        return (
            <div className="child">
                <h2>我是Child组件</h2>
                <span>我接到的车是:{this.props.carName}</span>
            </div>
        );
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值