首頁 > web前端 > js教程 > 主體

操作render執行有哪些方法

php中世界最好的语言
發布: 2018-04-28 13:36:06
原創
2345 人瀏覽過

這次帶給大家操作render執行有哪些方法,操作render執行的注意事項有哪些,下面就是實戰案例,一起來看一下。

我們都知道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 (
      
    );
  }
}
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 (
      
    )
  }
}
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的。

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

右側帶索引通訊錄實作(附程式碼)

vue-ssr靜態網站生成器VuePress使用詳解

以上是操作render執行有哪些方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!