封装成子组件

    //导入react
    import React from 'react'
    import ReactDOM from 'react-dom'
     
    //导入组件
    // 约定1:类组件必须以大写字母开头
    // 约定2:类组件应该继承react.component父类 从中可以使用父类的方法和属性
    // 约定3:组件必须提供render方法
    // 约定4:render方法必须有返回值
    class NumberBox extends React.Component{
        shouldComponentUpdate(nextProps,nextState){
            //根据条件判断渲染true或者false
            //如果前后两次数据相同就不用render
       

if(nextProps.number===this.props.number){
return false
}
return true

}
render(){
return <h1>随机数:{this.props.number}h1>
}
}
class App extends React.Component {
constructor(props) {
super(props)
console.log('生命周期钩子函数:construtor')
}
state={
number:0
}



handleClick=()=>{
this.setState(()=>{
return {
number:Math.floor(Math.random()*3)
}
}
)
}

render() {
console.log('生命周期钩子函数:render')
console.log(this.props,"props")
return (
<div id="title">
<NumberBox number={this.state.number}>NumberBox>
<button onClick={this.handleClick}>重新生成button>
div>
)
}
}



ReactDOM.render(<App>App>, document.getElementById('root'))

运行结果

好客租房84-组件性能优化(4减少不必要的渲染)_父类