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

封装成子组件

    //导入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'))

运行结果

posted @   前端导师歌谣  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示