React 性能检测
安装 react 性能检测工具 npm i react-addons-perf --save, 然后在初始化项目的./app/index.js 中写入以下代码:
- // 性能检测
- import Perf from 'react-addons-perf'
- if(_DEV_){
- window.Perf=Perf
- }
在运行之前, 先让 react 项目启动起来, 然后打开开发者调试面板, 在 console 中输入 Perf.start() 开始检测, 在页面上进行若干的操作以后, 执行 Perf.end(), 终止检测操作, 然后执行 Perf.printWasted(), 在 console 中会打印出操作过程的一个列表展示本次性能结果. 在实际项目开发中经常会使用它查看项目的性能情况.
如果性能影响不是很大, 例如每次操作就消耗几秒到几十毫秒, 那就不必纠结. 但是如果浪费过多时间影响到其用户体验, 那我们就必须搞定它.
PureRenderMixin 优化
react 最常用的工具就是 PureRenderMixin, 使用 npm i react-addons-pure-render-mixin --save, 安装并使用:
- import React,{Component} from 'react'
- import PureRenderMixin from 'react-addons-pure-render-mixin'
- class Demo extends Component{
- constructor(props){
- super(props)
- this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this)
- }
- // 省略其他代码....
- }
react 的生命周期 hook 中有个 shouldComponentUpdate, 组件每一次改动, 都要问一下这个函数是否要执行更新, 当这个函数返回 true, 则执行更新. 返回 false, 则不执行更新. 默认的情况下, 这个函数一直会返回 true, 即一些无效的更新也会执行.
为什么会有无效的改动? 我们都知道, 在 react 组件中, state 和 props 的改变都会触发组件的更新和重新渲染. 但是在 react 中有些时候 state 和 props 没有改变也会触发更新. 这样就会导致无效的渲染.
这里使用 this.shouldComponentUpdate=PureRenderMixin.shouldComponentUpdate.bind(this), 实际上是对组件原来的 shouldComponentUpdate 的方法进行重写, 每次更新之前都要查看 props 和 state 的是否发生改变, 如果改变; 就返回 false, 没有就返回 true.
所以我们在 react 开发中都尽量在组件中加入 PureRenderMixin 方法去优化性能.
来源: https://juejin.im/post/5b10dcc35188257d367e53cc