性能檢測
- 安裝 react 性能檢測工具 npm i react-addons-perf --save,然后在./app/index.jsx中
// 性能測試
import Perf from 'react-addons-perf'
if (__DEV__) {
window.Perf = Perf
}
運行程序。在操作之前先運行Perf.start()開始檢測,然后進行若干操作,運行Perf.stop停止檢測,然后再運行Perf.printWasted()即可打印出浪費性能的組件列表。在項目開發(fā)過程中,要經常使用檢測工具來看看性能是否正常。
如果性能的影響不是很大,例如每次操作多浪費幾毫秒、十幾毫秒,個人以為沒必要深究,但是如果浪費過多影響了用戶體驗,就必須去搞定它。
PureRenderMixin 優(yōu)化
- React 最基本的優(yōu)化方式是使用PureRenderMixin,安裝工具 npm i react-addons-pure-render-mixin --save,然后在組件中引用并使用
import React from 'react'import PureRenderMixin from 'react-addons-pure-render-mixin'
class List extends React.Component {
constructor(props, context) {
super(props, context);
this.shouldComponentUpdate =
PureRenderMixin.shouldComponentUpdate.bind(this);
} //...省略其他內容...}
React 有一個生命周期 hook 叫做shouldComponentUpdate,組件每次更新之前,都要過一遍這個函數(shù),如果這個函數(shù)返回true則更新,如果返回false
則不更新。而默認情況下,這個函數(shù)會一直返回true,就是說,如果有一些無效的改動觸發(fā)了這個函數(shù),也會導致無效的更新那么什么是無效的改動?之前說過,組件中的props和state一旦變化會導致組件重新更新并渲染,但是如果props和state沒有變化也莫名其妙的觸發(fā)更新了呢(這種情況確實存在)———— 這不就導致了無效渲染嗎?
這里使用this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
的意思是重寫組件的shouldComponentUpdate
函數(shù),在每次更新之前判斷props和state,如果有變化則返回true,無變化則返回false。
因此,我們在開發(fā)過程中,在每個 React 組件中都盡量使用PureRenderMixin