State & 生命周期
最后更新于:2022-04-02 03:33:34
[TOC]
## 概述
State 与 props 类似,但是 state 是私有的,并且完全受控于当前组件。
## state
```
//赋值
this.state={date:new Date()}
//更新
this.setState({date:new Date()});
```
### State 的更新可能是异步的
```
//error
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
```
## 例子
### 一个定时器demo
```
class App extends Component {
constructor(props) {
super(props);
// this.state={date:new Date()}
this.state={date:new Date()}
}
//组件被渲染到DOM后执行
componentDidMount() {
this.timeId = setInterval(()=>this.tick(),1000);
}
componentWillUnmount() {
clearInterval(this.timeId);
}
tick() {
this.setState({date:new Date()});
}
render() {
return (
);
}
}
```
';
Edit src/App.js
and save to reload.
time {this.state.date.toLocaleTimeString()}