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

首頁 > 開發 > JS > 正文

React中的render何時執行過程

2024-05-06 16:43:44
字體:
來源:轉載
供稿:網友

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

存在期的方法包含:

  1. - componentWillReceiveProps
  2. - shouldComponentUpdate
  3. - componentWillUpdate
  4. - render
  5. - 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方法會被執行嗎?

react,render,執行過程,執行,react中的render

如圖所示,當我們點擊button時,子組件的render方法被執行了。可是從代碼來看,組件綁定的onClick和text都沒有發生改變啊,為何組件會更新呢?

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

react,render,執行過程,執行,react中的render

是的,你沒有看錯,輸出的是false。這也是為什么子組件會更新了,因為屬性值發生了變化,并不是說我們綁定在組件上的屬性值。每次點擊button時會觸發state發生變化,進而整個組件重新render了,但這并不是我們想要的,因為這不必要的渲染會極其影響我們應用的性能。

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

class HelloWorldComponent extends React.PureComponent 

這次在點擊button時發生了什么呢?

react,render,執行過程,執行,react中的render
  

雖然componentWillReceiveProps依然會執行,但是這次組件沒有重新render。

所以,我們對于無狀態組件,我們應該盡量使用PureComponent,需要注意的是PureComponent只關注屬性值,也就意味著對象和數組發生了變化是不會觸發render的。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沾化县| 防城港市| 广汉市| 健康| 临汾市| 邯郸县| 潼南县| 平邑县| 康定县| 襄汾县| 兴安盟| 衢州市| 邵阳市| 和平县| 江达县| 仁怀市| 宁远县| 温州市| 遵化市| 兴文县| 西藏| 阳谷县| 毕节市| 离岛区| 元江| 阿坝| 长兴县| 天长市| 横峰县| 巫溪县| 灵璧县| 娱乐| 军事| 云南省| 青铜峡市| 临湘市| 龙门县| 漾濞| 武山县| 开化县| 棋牌|