好客租房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'))
运行结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南