React中的render何時執(zhí)行過程
我們都知道Render在組件實例化和存在期時都會被執(zhí)行。實例化在componentWillMount執(zhí)行完成后就會被執(zhí)行,這個沒什么好說的。在這里我們主要分析存在期組件更新時的執(zhí)行。
存在期的方法包含:
- - componentWillReceiveProps
- - shouldComponentUpdate
- - componentWillUpdate
- - render
- - componentDidUpdate
這些方法會在組件的狀態(tài)或者屬性發(fā)生發(fā)生變化時被執(zhí)行,如果我們使用了Redux,那么就只有當(dāng)屬性發(fā)生變化時被執(zhí)行。下面我們將從幾個場景來分析屬性的變化。
首先我們創(chuàng)建了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。
這個時候當(dāng)我們點擊button時,你覺得子組HelloWorldComponent的render方法會被執(zhí)行嗎?
如圖所示,當(dāng)我們點擊button時,子組件的render方法被執(zhí)行了??墒菑拇a來看,組件綁定的onClick和text都沒有發(fā)生改變啊,為何組件會更新呢?
如果在子組件的componentWillReceiveProps添加這個log:console.log(‘isEqual', nextProps === this.props); 輸出會是true還是false呢?
是的,你沒有看錯,輸出的是false。這也是為什么子組件會更新了,因為屬性值發(fā)生了變化,并不是說我們綁定在組件上的屬性值。每次點擊button時會觸發(fā)state發(fā)生變化,進(jìn)而整個組件重新render了,但這并不是我們想要的,因為這不必要的渲染會極其影響我們應(yīng)用的性能。
在react中除了繼承Component創(chuàng)建組件之外,還有個PureComponent。通過該組件就可以避免這種情況。下面我們對代碼做點修改再來看效果。修改如下:
class HelloWorldComponent extends React.PureComponent
這次在點擊button時發(fā)生了什么呢?
雖然componentWillReceiveProps依然會執(zhí)行,但是這次組件沒有重新render。
所以,我們對于無狀態(tài)組件,我們應(yīng)該盡量使用PureComponent,需要注意的是PureComponent只關(guān)注屬性值,也就意味著對象和數(shù)組發(fā)生了變化是不會觸發(fā)render的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于React實現(xiàn)表單數(shù)據(jù)的添加和刪除詳解
這篇文章主要給大家介紹了基于React實現(xiàn)表單數(shù)據(jù)的添加和刪除的方法,文中給出了詳細(xì)的示例供大家參考,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03
react antd如何防止一份數(shù)據(jù)多次提交
這篇文章主要介紹了react antd如何防止一份數(shù)據(jù)多次提交問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Hello?React的組件化方式之React入門小案例演示
這篇文章主要介紹了Hello?React的組件化方式-React入門小案例,本文通過Hello?React的案例,?來體驗一下React開發(fā)模式,?以及jsx的語法,需要的朋友可以參考下2022-10-10
使用React hook實現(xiàn)remember me功能
相信大家在使用 React 寫頁面的時候都遇到過完成 Remember me 的需求吧!本文就將這個需求封裝在一個 React hook 中以供后續(xù)的使用,覺得有用的同學(xué)可以收藏起來以備不時之需,感興趣的小伙伴跟著小編一起來看看吧2024-04-04
D3.js(v3)+react 實現(xiàn)帶坐標(biāo)與比例尺的柱形圖 (V3版本)
這篇文章主要介紹了D3.js(v3)+react 制作 一個帶坐標(biāo)與比例尺的柱形圖 (V3版本) ,本文通過實例代碼文字相結(jié)合的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2019-05-05

