问题
- 只要执行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>   
                <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;
}
 
效果实现:
 









![[量化投资-学习笔记007]Python+TDengine从零开始搭建量化分析平台-布林带](https://img-blog.csdnimg.cn/b50e5c39bb1d44c1a12fb9e495e79c67.png)



![[PHP]得推跑腿O2O系统 v3.41](https://img-blog.csdnimg.cn/e2c4016d67b146138e27e949f476e217.png)





