您的位置:首页 > Web前端 > React

react 初探:类组件、状态和生命周期

2018-02-13 14:15 756 查看
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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: