[关闭]
@windchimes 2019-03-19T02:26:39.000000Z 字数 1397 阅读 270

react性能优化点

前端知识点总结


主要优化点:

1)shouldComponentUpdate(nextProps,nextState)函数
优化方法:缩短此函数的执行比较时间;不必要的渲染,直接返回false
此方法里可以使用浅比较,也可以使用PureComponent来代替。实际项目中,需要深比较的时候,可以考虑使用immutable.js
它的职责是返回true或者false来决定是否要re-render,可以在它里面使用immutable.js,可极大的提高性能:immutable.js特点:持久化数据结构、结构共享
react 15.3引入了一个新的PureComponent组件,它进行了一次浅比较,也就是说会比较Object.keys(state | props)的长度是否一致,每一个key是否两者都有,并且是否是一个引用等
  1. import { is } from 'immutable'
  2. shouldComponentUpdate: (nextProps = {}, nextState = {}) => {
  3. const thisProps = this.props || {}
  4. const thisState = this.state || {}
  5. if (Object.keys(thisProps).length !== Object.keys(nextProps).length || Object.keys(thisState).length !== Object.keys(nextState).length)) {
  6. return true;
  7. }
  8. }
  9. for (const key in nextProps) {
  10. if(!is(thisProps[key], nextProps[key])) {
  11. return true;
  12. }
  13. }
  14. for (const key in nextState) {
  15. if (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) {
  16. return true;
  17. }
  18. return false;
  19. }
2)this.handlechange.bind(this)尽量在constructor里面来绑定,不要直接在组件中做,因为每次re-render的时候,即使props没有改变,它依旧会re-render,immutable.js也不好使,因为每次父组件render,都会执行子组件的bind方法
3){...this.props} 尽量不要使用,只传递component需要的props和state,传的太多或者层级太深,都会加重shouldComponentUpdate的数据比较负担
4)复杂的页面不要在一个组件里写完
5)map里面添加key,并且key值不要使用index(可变的)
6)尽量少使用settimeout或者不可控的refs dom操作等
7)数据尽可能简单明了,扁平化
8)不变的html代码可以抽离出来直接当做一个变量,写在jsx里,jsx会把它当做一个值,减少了解析过程

相关链接:https://www.cnblogs.com/little-ab/articles/6971269.html
https://segmentfault.com/a/1190000008925295
http://blog.csdn.net/sinat_17775997/article/details/77979679

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注