iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 7
0
Modern Web

30天React從入門到入坑系列 第 7

DAY7:React Lifecycle

https://ithelp.ithome.com.tw/upload/images/20171226/20107317h7GJBFtAJb.png

Mounting
getDefaultProps-->getInitialState-->componentWillMount-->render
-->componentDidMount

Updating
componentWillReceiveProps-->shouldComponentUpdate-->componentWillUpdate
-->render-->componentDidUpdate

Unmounting
componentWillUnmount

  • componentWillMount:插入DOM前呼叫
  • componentDidMount:插入DOM後呼叫
  • componentWillUnmount:remove元素後呼叫
  • componentWillUpdate:更新元素前呼叫
  • componentDidUpdate:更新元素後呼叫
  • shouldComponentUpdate:此method回傳true才會更新DOM,回傳false則停止更新
src/SayHi.js

import React, { Component } from 'react';

class SayHi extends React.Component {
  constructor(props) {
    super(props);
    console.log('constructor');
    this.handleClick = this.handleClick.bind(this);
    this.state = {date: new Date()};
  }

  handleClick() {
    this.setState({date: new Date()});
  }

  componentWillMount() {
    console.log('componentWillMount');
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  componentWillReceiveProps() {
    console.log('componentWillReceiveProps');
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate');
    console.log('nextProps:'+nextProps.name);
    console.log('nextState:'+nextState.date);
    return true;
  }

  componentWillUpdate() {
    console.log('componentWillUpdate');
  }

  componentDidUpdate() {
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  render() {
    return <h1 onClick={this.handleClick}>{this.state.date.toLocaleTimeString()} Hi, {this.props.name}</h1>;
  }
}

export default SayHi;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import SayHi from './SayHi';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<SayHi name="John" />, document.getElementById('root'));
registerServiceWorker();

console.log
constructor
componentWillMount
componentDidMount
https://ithelp.ithome.com.tw/upload/images/20171226/20107317wiYlamEIbk.png

測試請點擊"h1"元素觸發onClick事件更新畫面,shouldComponentUpdate印出nextProps和nextState,假設回傳值為false則不會更新畫面,所以在撰寫程式可在這判斷是否要更新畫面。
console.log
shouldComponentUpdate
nextProps:John
nextState:Tue Dec 26 2017 15:35:34 GMT+0800 (台北標準時間)
componentWillUpdate
componentDidUpdate
https://ithelp.ithome.com.tw/upload/images/20171226/201073171OiAxEsmit.png


上一篇
DAY6:state與資料流
下一篇
DAY8:Handling Events
系列文
30天React從入門到入坑30

尚未有邦友留言

立即登入留言