React.PureComponent(React組件優化之淺比較)

React.PureComponent(React組件優化)

React.PureComponent:

就是基於淺比較的方式,給每個組件設置shouldComponentUpdate(若是本身設置了,以本身的爲主),在裏面把狀態和屬性都作對比,若是二者基於淺比較都沒有發生任何的更改,則再也不從新渲染組件react

setStart有個小毛病

雖說是改變狀態而且通知組件從新渲染,可是咱們不改狀態值,也通知組件從新渲染了shouldComponentUpdate => componentWillUpdate ...
 
forceUpdate:=>componentWillUpdate (跳過SHOULD步驟)
複製代碼
  • 好了!咱們先經過一個小案例感覺一下PureComponent部分源碼,
import React from 'react';
import PropTypes from 'prop-types';

/*
 * React.PureComponent
 */
//=>把兩個對象進行淺比較
// 只比較對象的第一級
// 若是屬性值是基本類型的,咱們只須要比較值是否同樣便可
function shallowEqual(obj1, obj2) {
	if (Object.keys(obj1).length !== Object.keys(obj2).length) {
		return false;
	}
	for (let key in obj1) {
		if (obj1[key] !== obj2[key]) {
			return false;
		}
	}
	return true;
}
class CountShow extends React.Component {
	render() {
		return <div>
			{this.props.num}
		</div>;
	}
}
export default class Count extends React.Component {
	state = {
		num: 0,
		x: 100,
		arr: [10, 20]
	};
	render() {
		console.log('OK');
		return <>
			<CountShow num={this.state.num} />
			<button onClick={ev => {
				this.state.arr.push(30);
				this.setState({
					arr: [...this.state.arr]
				});
			}}>累加</button>
		</>;
	}
	shouldComponentUpdate(nextProps, nextState) {
		return !shallowEqual(this.state, nextState) || !shallowEqual(this.props, nextProps);
	}
}

複製代碼

淺比較就是隻比較第一級,對於基本數據類型,只比較值;對於引用數據類型值,直接比較地址是否相同,無論裏面內容變不變,只要地址同樣,咱們就認爲沒變。因此在這種狀況下,咱們之後用的時候,對於引用類型值修改狀態或修改屬性時候,對於它賦值的時候,咱們儘量把以前值拿過來克隆一份,賦給它新的地址就好~這是咱們的注意點!咱們想作性能優化的時候就能夠在Component裏作一個淺比較。性能優化

=>React.PureComponent是基於淺比較,因此只要屬性值是引用類型,可是修改後的值變了,可是地址不變,也不會從新渲染bash

如下這段是註釋---
/*
  	 this.state.arr.push(30)
    setState({
        arr:this.state.arr 不會通知從新渲染
       arr:[...this.state.arr] 這樣是會通知的(堆內存地址變了)
    })
=>PureComponent對forceUpdate無效(forceUpdate根本不走shouldComponentUpdate)
=>父組件是PureComponent那麼子組件也具有了一樣的功效(由於父組件不渲染,子組件也不會渲染)

*/
複製代碼

PureComponent使用方法

  • 仍是用一樣的小案例,不過比本身寫方法方便的多,直接把React.Component替換成React.PureComponent便可~
import React from 'react';
import PropTypes from 'prop-types';

class CountShow extends React.Component {
   render() {
   	return <div>
   		{this.props.num}
   	</div>;
   }
}
export default class Count extends React.PureComponent {
   state = {
   	num: 0,
   	x: 100,
   	arr: [10, 20]
   };
   render() {
   	console.log('OK');
   	return <>
   		<CountShow num={this.state.num} />
   		<button onClick={ev => {
   			this.state.arr.push(30);
   			this.setState({
   				arr: [...this.state.arr]
   			});
   		}}>累加</button>
   	</>;
   }
}
複製代碼

注意

  • 注:PureComponent不能亂用,只有那些狀態和屬性不常常的更新的組件咱們用來作優化,對於常常更新的,這樣處理後反而浪費性能,由於每一次淺比較也是要消耗時間的
相關文章
相關標籤/搜索