react之Component存在的2个问题

问题

  • 只要执行setState(),即使不改变状态数据,组件也会重新render()
  • 只当前组件重新render(),就会自动重新render子组件

原因

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

思路

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

解决

  • 重写shouldComponentUpdate()方法:比较新旧state或props数据,如果有变化才返回true,如果没有返回false
  • 使用PureComponent:PureComponent重写了shouldComponentUpdate()方法,只有state或props数据有变化才返回true。(只进行state和props数据的浅比较,如果只是数据对象数据变了,返回false)

案例

import React, { PureComponent } from 'react'
import './index.css'

export default class Parent extends PureComponent {
    state = { carName: '奔驰' }
    changeCar = ()=>{
        this.setState({carName:'五菱'})
    }
    // shouldComponentUpdate(nextProps,nextState){
    //     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);
    //     return !(this.state.carName === nextState.carName)
    // }
    render() {
        console.log('Parent-render');
        const { carName } = this.state
        return (
            <div className='parent'>
                <h5>parent组件</h5>
                <span>我的车是:{carName}</span>&nbsp;&nbsp;&nbsp;
                <button onClick={this.changeCar}>换车</button>
                <Child car='木马'></Child>
            </div>
        )
    }
}

class Child extends PureComponent {
    // shouldComponentUpdate(nextProps,nextState){
    //     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);
    //     return !(this.props.car === nextProps.car)
    // }
    render() {
        console.log('Child-render');
        return (
            <div className='child'>
                <h5>child组件</h5>
                <div>Child组件从Parent组件拿到的车是:{this.props.car}</div>
            </div>
        )
    }
}	

样式文件:

.parent{
    width: 500px;
    background-color: aqua;
    padding: 20px;
}

.child{
    width: 90%;
    background-color:bisque;
    padding: 20px;
    margin-top: 30px;
}

效果实现:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值