1. 程式人生 > >React中的render何時執行

React中的render何時執行

  我們都知道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的。