React 把組件看成是一個狀態(tài)機(State Machines)。通過與用戶的交互,實現(xiàn)不同狀態(tài),然后渲染 UI,讓用戶界面和數(shù)據(jù)保持一致。
React只需更新組件的 state,然后根據(jù)新的 state 重新渲染用戶界面(不要操作 DOM)。
創(chuàng)建一個名稱擴展為 React.Component 的 ES6 類,在 render() 方法中使用 this.state 來修改當前的時間。
添加一個類構(gòu)造函數(shù)來初始化狀態(tài) this.state,類組件應始終使用 props 調(diào)用基礎(chǔ)構(gòu)造函數(shù)。
class Clock extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.state = {date: new Date()};
? }
? render() {
? ? return (
? ? ? <div>
? ? ? ? <h1>Hello, world!</h1>
? ? ? ? <h2>現(xiàn)在是 {this.state.date.toLocaleTimeString()}.</h2>
? ? ? </div>
? ? );
? }
}
ReactDOM.render(
? <Clock />,
? document.getElementById('example')
);
將使Clock設(shè)置自己的計時器并每秒更新一次。將生命周期方法添加到類中,在具有許多組件的應用程序中,在銷毀時釋放組件所占用的資源非常重要。
每當 Clock 組件第一次加載到 DOM 中的時候,都想生成定時器,這在 React 中被稱為掛載。同樣,每當 Clock 生成的這個 DOM 被移除的時候,也會想要清除定時器,這在 React 中被稱為卸載。
可以在組件類上聲明特殊的方法,當組件掛載或卸載時,來運行一些代碼:
React 實例
class Clock extends React.Component {
? constructor(props) {
? ? super(props);
? ? this.state = {date: new Date()};
? }
? componentDidMount() {
? ? this.timerID = setInterval(
? ? ? () => this.tick(),
? ? ? 1000
? ? );
? }
? componentWillUnmount() {
? ? clearInterval(this.timerID);
? }
? tick() {
? ? this.setState({
? ? ? date: new Date()
? ? });
? }
? render() {
? ? return (
? ? ? <div>
? ? ? ? <h1>Hello, world!</h1>
? ? ? ? <h2>現(xiàn)在是 {this.state.date.toLocaleTimeString()}.</h2>
? ? ? </div>
? ? );
? }
}
ReactDOM.render(
? <Clock />,
? document.getElementById('example')
);
componentDidMount() 與 componentWillUnmount() 方法被稱作生命周期鉤子。
在組件輸出到 DOM 后會執(zhí)行 componentDidMount() 鉤子,就可以在這個鉤子上設(shè)置一個定時器。
this.timerID 為定時器的 ID,可以在 componentWillUnmount() 鉤子中卸載定時器。