国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

React中的render何時(shí)執(zhí)行過程

2019-11-19 14:01:25
字體:
供稿:網(wǎng)友

我們都知道Render在組件實(shí)例化和存在期時(shí)都會(huì)被執(zhí)行。實(shí)例化在componentWillMount執(zhí)行完成后就會(huì)被執(zhí)行,這個(gè)沒什么好說的。在這里我們主要分析存在期組件更新時(shí)的執(zhí)行。

存在期的方法包含:

  1. - componentWillReceiveProps
  2. - shouldComponentUpdate
  3. - componentWillUpdate
  4. - render
  5. - componentDidUpdate

這些方法會(huì)在組件的狀態(tài)或者屬性發(fā)生發(fā)生變化時(shí)被執(zhí)行,如果我們使用了Redux,那么就只有當(dāng)屬性發(fā)生變化時(shí)被執(zhí)行。下面我們將從幾個(gè)場景來分析屬性的變化。

首先我們創(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方法會(huì)每次點(diǎn)擊時(shí)將count加1。

這個(gè)時(shí)候當(dāng)我們點(diǎn)擊button時(shí),你覺得子組HelloWorldComponent的render方法會(huì)被執(zhí)行嗎?

 

如圖所示,當(dāng)我們點(diǎn)擊button時(shí),子組件的render方法被執(zhí)行了。可是從代碼來看,組件綁定的onClick和text都沒有發(fā)生改變啊,為何組件會(huì)更新呢?

如果在子組件的componentWillReceiveProps添加這個(gè)log:console.log(‘isEqual', nextProps === this.props); 輸出會(huì)是true還是false呢?

 

是的,你沒有看錯(cuò),輸出的是false。這也是為什么子組件會(huì)更新了,因?yàn)閷傩灾蛋l(fā)生了變化,并不是說我們綁定在組件上的屬性值。每次點(diǎn)擊button時(shí)會(huì)觸發(fā)state發(fā)生變化,進(jìn)而整個(gè)組件重新render了,但這并不是我們想要的,因?yàn)檫@不必要的渲染會(huì)極其影響我們應(yīng)用的性能。

在react中除了繼承Component創(chuàng)建組件之外,還有個(gè)PureComponent。通過該組件就可以避免這種情況。下面我們對代碼做點(diǎn)修改再來看效果。修改如下:

class HelloWorldComponent extends React.PureComponent 

這次在點(diǎn)擊button時(shí)發(fā)生了什么呢?


  

雖然componentWillReceiveProps依然會(huì)執(zhí)行,但是這次組件沒有重新render。

所以,我們對于無狀態(tài)組件,我們應(yīng)該盡量使用PureComponent,需要注意的是PureComponent只關(guān)注屬性值,也就意味著對象和數(shù)組發(fā)生了變化是不會(huì)觸發(fā)render的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 蓝田县| 鄂托克前旗| 浙江省| 曲靖市| 舟山市| 凤阳县| 万荣县| 闻喜县| 冷水江市| 厦门市| 海南省| 陇川县| 滦南县| 嘉兴市| 平湖市| 静乐县| 阿鲁科尔沁旗| 锡林郭勒盟| 密山市| 崇州市| 疏勒县| 滕州市| 绩溪县| 县级市| 犍为县| 河间市| 永清县| 长垣县| 陆良县| 绥阳县| 霸州市| 张家川| 佛教| 顺昌县| 宁安市| 牡丹江市| 贡觉县| 义乌市| 梅州市| 新河县| 秭归县|