State
顾名思义,state用于表示组件的状态。相当于组件的私有变量,只可以在组件内部修改,完全受控于当前组件。
是由类定义的组件所特有的。
状态的声明
class Clock extends React.Component{
constructor(props){
super(props);
this.state = {date:new Date()};//对state进行初始化
}
render(){//类组件唯一必须的方法
return (<div>
<p>hello world</p>
<h2>{this.state.date.toLocaleTimeString()}</h2>
</div>);
}
}
如果想要实现实时更新的时钟,那就需要与生命周期的钩子函数结合。
生命周期:
1.初始化
constructor()
2.挂载
static getDerivedStateFromProps()
组件实例化后和属性更新后
render()
componentDidMount()
组件挂载后立即调用
3.更新
static getDerivedStateFromProps()
shouldComponentUpdate()
接收到新属性和状态时,渲染前调用,返回布尔值,决定是否更新
render()
getSnapshotBeforeUpdate()
渲染提交给DOM之前调用,返回值传给componentDidUpdate(),可以返回null
componentDidUpdate()
4.卸载
componentWillUnmount()
5.错误处理
componentDidCatch()
在挂载后新建一个定时器,在卸载时清除定时器,利用this.setState()就可以实现实时时钟。
class Clock extends React.Component{
constructor(props){
super(props);
this.state = {date:new Date()};//对state进行初始化
}
tick(){
this.setState({date:new Date()})
}
//挂载
componentDidMount() {
console.log('4-componentDidMount');
this.timerID = setInterval(
() => this.tick(),
1000);
}
//卸载
componentWillUnmount(){
clearInterval(this.timerID);
}
render(){//类组件唯一必须的方法
return (<div>
<p>hello world</p>
<h2>{this.state.date.toLocaleTimeString()}</h2>
</div>);
}
}
ReactDOM.render(<Clock />,document.getElementById('root'));
用this.setState({})来更新state,constructor()中初始化state