我們都知道Render在組件實例化和存在期時都會被執行。實例化在componentWillMount執行完成後就會被執行,這個沒什麽好說的。在這裏我們主要分析存在期組件更新時的執行。
存在期的方法包含:
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
這些方法會在組件的狀態或者屬性發生發生變化時被執行,如果我們使用了Redux,那麽就只有當屬性發生變化時被執行。下面我們將從幾個場景來分析屬性的變化。
首先我們創建了HelloWorldComponent,代碼如下所示:
import * as React from "react";
class HelloWorldComponent extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
console.log('hello world componentWillReceiveProps');
}
render() {
console.log('hello world render');
const { onClick, text } = this.props;
return (
<button onClick={onClick}>
{text}
</button>
);
}
}
HelloWorldComponent.propTypes = {
onClick: React.PropTypes.func,
};
export default HelloWorldComponent;AppComponent組件的代碼如下:
class MyApp extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
console.log('button click');
this.props.addNumber();
}
render() {
return (
<HelloWorld onClick={this.onClick} text="test"></HelloWorld>
)
}
}
const mapStateToProps = (state) => {
return { count: state.count }
};
const mapDispatchToProps = {
addNumber
};
export default connect(mapStateToProps, mapDispatchToProps)(MyApp);這裏我們使用了Redux,但是代碼就不貼出來了,其中addNumber方法會每次點擊時將count加1。
這個時候當我們點擊button時,妳覺得子組HelloWorldComponent的render方法會被執行嗎?
如圖所示,當我們點擊button時,子組件的render方法被執行了。可是從代碼來看,組件綁定的onClick和text都沒有發生改變啊,為何組件會更新呢?
如果在子組件的componentWillReceiveProps添加這個log:console.log(‘isEqual', nextProps === this.props); 輸出會是true還是false呢?
是的,妳沒有看錯,輸出的是false。這也是為什麽子組件會更新了,因為屬性值發生了變化,並不是說我們綁定在組件上的屬性值。每次點擊button時會觸發state發生變化,進而整個組件重新render了,但這並不是我們想要的,因為這不必要的渲染會極其影響我們應用的性能。
在react中除了繼承Component創建組件之外,還有個PureComponent。通過該組件就可以避免這種情況。下面我們對代碼做點修改再來看效果。修改如下:
class HelloWorldComponent extends React.PureComponent這次在點擊button時發生了什麽呢?
雖然componentWillReceiveProps依然會執行,但是這次組件沒有重新render。
所以,我們對於無狀態組件,我們應該盡量使用PureComponent,需要註意的是PureComponent只關註屬性值,也就意味著對象和數組發生了變化是不會觸發render的。
相信看了本文案例妳已經掌握了方法,更多精彩請關註Gxl網其它相關文章!
推薦閱讀:
右側帶索引通訊錄實現(附代碼)
vue-ssr靜態網站生成器VuePress使用詳解