React.Component 和 React.PureComponent 、React.memo 的区别
一 结论
React.Component 是没有做任何渲染优化的,但凡调用this.setState 就会执行render的刷新操作。
React.PureComponent 是继承自Component,并且对重写了shouldComponentUpdate周期函数,对 state 和 props 做了浅层比较,当state 和 props 均没有改变时候,不会render,仅可以用在ClassComponent中
React.memo 功能同React.PureComponent,但React.memo 为高阶组件,既可以用在ClassComponent中 也可以用在 functionComponent中
二 React.Component
需要手动编写shouldCompoentUpdate进行 props和state的比较判断是否需要渲染render
Class Sum extends React.Component {
constructor(props){
super(props);
this.state = {
num:0
}
}
shouldCompoentUpdate(nextProps,nextState){
if(nextPorps.sum === this.props.sum && nextState.num === this.state.num){
return false; // 当props 和state 值均没有改变时候,让render不渲染
}
return ture; // 其他情况设置成允许渲染
}
render(){
return (
<div>
<span>{this.state.num}</span>
<span>{this.props.sum}</span>
</div>
)
}
}
二 React.PureComponent 和 React.memo 的使用
Class Sum extends React.PureComponent {
// 会自动进行props 和 sate 的浅比较
}
function Add (props){
return (
<div>sum = {props.y + props.x}</div>
)
}
export default React.memo(Add)
注意:当props 或者 state 为一个 Object类型时候,浅比较会失效 即 props ,state 发生改变,依旧会阻止render渲染。
此时可以运用的方法有
1 修改state时候,采用 object.assin({},)进行组件合并
2 采用 解构赋值进行浅拷贝赋值,这样props或者state 就不再为原来的值了,可以触发render刷新操作
3 当组件结构较复杂,存在较多 Object类型时候 建议改为使用React.Component
分类:
react技术栈
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具