Lifecycle - ly-yuan-kai/Demo GitHub Wiki

在官方的documents中,使用到跟生命週期相關的兩個functioncomponentDidMount, componentWillUnmount

componentDidMount():這個function是在component render完頁面後觸發。

componentWillUnmount():當元件準備要被移除或破壞時觸發。

this.setState(): function觸發後會重繪一次頁面。

禁止在render()中使用this.setState(),會造成無限重繪頁面。

//Clock.js 

class Clock extends Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
    console.log('Clock is closed.');
  }

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

  render() {
    return (
      <div>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

在生命週期中,render()方法於頁面中最先被執行,完畢後則會觸發componentDidMount(),因componentDidMount()中執行setState(), 在上述提到因執行完setState()會讓頁面重新render一次,所以Clock.js才可以讓頁面維持是現在的時間。

⚠️ **GitHub.com Fallback** ⚠️