学习React系列(五)——使性能最优
2024-08-26 09:43:23
提高性能可分为两方面:
一、配置层面
二、代码层面
本文只从代码层面考虑:
一、避免重复渲染
这里要说一句:
当shouldComponentUpdate返回false的时候不触发render函数也就无法造成渲染
触发render之后react发现原来的dom与现在的dom一致,将不触发更新
如何避免重复渲染呢?
其实就是在shouldComponentUpdate方法中进行if判断,特定条件下才允许返回true
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
} shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
} render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
React提供了一个辅助对象来实现这个逻辑 - 继承自React.PureComponent,当state中的值改变的时候才可以触发render。但要注意,这里仅仅是浅比较。
如果需要进行深比较,那么有两种方法
一、创建新的对象,然后进行setstate操作(推荐理由:完全不需要再引一个库吧)
function updateColorMap(colormap) {
return Object.assign({}, colormap, {right: 'blue'});
}
this.setState(prevState => ({
words: prevState.words.concat(['marklar'])
}));
二、使用不可突变的数据结构Immutable.js
参考:https://reactjs.org/docs/optimizing-performance.html
最新文章
- svn忽略某个文件提交
- windows下使用vs进行Proctocol Buffer开发(C++篇)
- .net开发过程中遇到的错误,及解决办法记录
- Java工厂设计模式
- c#与.net的简介
- Hello World for U
- Linux堆内存管理深入分析
- ANDROID_MARS学习笔记_S01原始版_004_TableLayout
- Java 授权内幕--转载
- Centos 5.5 安装Mysql5.5过程
- Java(基础)的类与变量
- luogu3244 bzoj4011 HNOI2015 落忆枫音
- HTMl、CSS、JS的区别:
- 键盘上的";整蛊专家";,如何防止短信轰炸机
- JavaWeb工程中web.xml基本配置(转载学习)
- php 字符串截取,支持中文和其他编码
- CAT Caterpillar ET is really a exceptional obd2 solution
- Golang的文件处理方式-常见的读写姿势
- 2018.07.28 uoj#169. 【UR #11】元旦老人与数列(线段树)
- 菜单Menu(AS开发实战第四章学习笔记)
热门文章
- 造轮子-Java泛型堆排
- color 圆盘染色
- 访问限制:由于对必需的库 C:/Program Files/Java/jre6/lib/rt.jar 具有一定限制,因此无法访问类型。。
- Java 并发基础——线程安全性
- 个人作业Week3-案例分析
- alpha-咸鱼冲刺day8-紫仪
- 201621123043《java程序设计》第五周学习总结
- collections deque队列及其他队列
- OSI七层协议模型、TCP/IP四层模型学习笔记
- bzoj千题计划113:bzoj1023: [SHOI2008]cactus仙人掌图