学习使用clock组件使代码可复用,从封装时钟开始:
function Clock(props) {
return(
<div>
<h1>hello,world</h1>
<h2>it is {props.date.toLocaleTimeString()}</h2>
</div>
);
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}
setInterval(tick,1000);
实际上clock应该自己实现定时和更新
用类定义的组件有一些额外的特性,指的就是局部状态
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')
);
在类中添加生命周期方法
class Clock extends React.Component {
constructor(props) {//类构造函数
super(props);
this.state = {date:new Date()};
}
ComponentDidMount() {//设置定时器timerID
this.timerID = setInterval(
() => this.tick(),
1000
);
}
ComponentWillUnmount(){//取消定时器timerID
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')
);
正确使用State状态
setState()
- 不要直接修改state
this.state.comment = 'hello';//错误
this.setState({comment:'hello'});//正确
唯一可以分配this.state的地方是构造函数
- state更新可能是异步的
将多个setState()调用合并为一次更新,接收一个函数,接收前一个状态值作为第一个参数,将更新后的值作为第二个参数
this.setState({
counter:this.state.counter+this.props.increment,
});//错误
this.setState(() => ({
counter:preState.counter+props.increment
}));//正确
this.setState(function(prevState,props) {
return{
counter:prevState.counter+props.increment
};
});
state状态更新会被合并
状态值可以单独更新
constructor(props){
super(props);
this.state = {
posts:[],
comments:[]
};
}
componentDidMount(){
fetchPosts().then(response =>{
this.setState({
posts:response.posts
});
});
fetchComments().then(response => {
this.setState({
comments:response.comments
});
});
}