react 初探:類元件、狀態和生命週期
阿新 • • 發佈:2018-12-06
react 除了提供函式式元件外,還提供了類元件,類元件提供了狀態屬性,下面一起吧之前的函式元件轉換成類元件。
/*
類元件定義
*/
class Clock extends React.Component{
render(){
return (
<div>
<h1>Hello,World</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
替換 render() 方法中的 this.props.date 為 this.state.date
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
新增類建構函式
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
經過修改之後的最終程式碼如下:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
這樣,當呼叫Clock元件時,能夠實現頁面上的具體時刻。但是這樣做還是有些問題,無法做到每秒鐘都更新元件,這裡不能像上一章節,直接採用setInterval(tick, 1000);的方式來進行每秒鐘更新,需要使用類元件提供的生命週期函式才可以。
類的生命週期
componentDidMount() 鉤子在元件輸出被渲染到 DOM 之後執行。我們將計時器的設定放在生命週期函式內。
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
當Clock元件DOM被清除時需要將計時器也銷燬,需要在結束生命週期函式中將該計時器銷燬。
componentWillUnmount() {
clearInterval(this.timerID);
}
最後,貼出整個流程的完整程式碼:
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>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
可以做到美妙都重新整理DOM。