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

这篇博客探讨了React组件的优化技巧,重点介绍了shouldComponentUpdate生命周期方法的使用,通过比较前后props来决定是否需要重新渲染,以提高应用性能。此外,还展示了如何创建一个简单的NumberBox组件,以及在App组件中如何更新状态并触发组件重新渲染。
摘要由CSDN通过智能技术生成

封装成子组件

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

运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值